Cannot save new users due to ValueError, Django

Multi tool use
Multi tool use


Cannot save new users due to ValueError, Django



I'm saving business hours to restaurants when they sign up on my platform but, I'm getting this error: "ValueError: save() prohibited to prevent data loss due to unsaved related object restaurant."



It was working prior and changed after I dropped my tables to start a new migration. Here is where the error is pointing to:


def restaurant_sign_up(request):
user_form = UserForm(request.POST or None)
restaurant_form = RestaurantForm(request.POST or None, request.FILES or None)

if request.method == "POST":
if user_form.is_valid() and restaurant_form.is_valid():
new_user = User.objects.create_user(**user_form.cleaned_data)
new_restaurant = restaurant_form.save(commit=False)

new_restaurant.user = new_user
new_restaurant.save()

login(request, authenticate(
username = user_form.cleaned_data["username"],
password = user_form.cleaned_data["password"],

))

for i in range(1, 8):
OpeningHours.objects.create(
restaurant=new_restaurant,
day_of_week=i,
opening_time="08:00",
closing_time="22:00"
)


return redirect(restaurant_home)

return render(request, 'restaurant/signup.html', {
"user_form": user_form,
"restaurant_form": restaurant_form,
# "hours_form": hours_form
})



The traceback points to the "closing_time="22:00"" as the issue. The hours of operations should just be created by default when



This is how the models are set up:


class OpeningHours(models.Model):
WEEKDAYS = [
(1, _("Monday")),
(2, _("Tuesday")),
(3, _("Wednesday")),
(4, _("Thursday")),
(5, _("Friday")),
(6, _("Saturday")),
(7, _("Sunday")),
]

day_of_week = models.IntegerField(choices=WEEKDAYS)
opening_time = models.TimeField()
closing_time = models.TimeField()
restaurant = models.ForeignKey('buddysapp.Restaurant', on_delete=models.CASCADE)

def __str__(self):
return self.get_day_of_week_display()

class Restaurant(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='restaurant')
restaurant_name = models.CharField(max_length=500, blank=False)
phone = models.CharField(max_length=500)
logo = models.ImageField(upload_to= 'restaurant_logo/', blank=False)


#Location
street_address = models.CharField(default = '',max_length = 50, null = True)
city = models.CharField(default='', max_length = 254,null=True,blank=True)
state = models.CharField(default = '',max_length=25, null = True)
zip_Code = models.IntegerField(null=False, default='')
lat = models.FloatField(default = "0.0", blank=True)
lng = models.FloatField(default = "0.0", blank=True)
latlng = models.CharField(blank=True, max_length=100)



def __str__(self):
return self.restaurant_name

## Geocode using full address
def _get_full_address(self):
return u'%s %s %s %s' % (self.street_address, self.city, self.state, self.zip_Code)
full_address = property(_get_full_address)


def super(Restaurant, self).save(*args, **kwargs):
if not self.latlng:
geolocator = Nominatim()
location = geolocator.geocode(self.full_address)
self.lat = location.latitude
self.lng = location.longitude
self.latlng = (location.latitude, location.longitude)
else:
location = '+'.join(filter(None, (self.street_address, self.city, self.state, self.zip_Code)))
self.latlng = get_lat_lng(location)
super(Restaurant, self).save(*args, **kwargs)



Any help would be appreciated.





Dupe: stackoverflow.com/questions/34503947/…
– dfundako
Jul 2 at 15:06





No. I'm not using InLineformset_factory here
– A True Novice
Jul 2 at 15:12





I don't understand at all what you've done with super() in the method declaration there. What in Alasdair's comment led you to think that was the right thing to do?
– Daniel Roseman
Jul 2 at 15:43



super()




1 Answer
1



Your Restaurant method does not call super(Restaurant, self).save(*args, **kwargs) in the if not self.latlng branch. That means that the restarant is not saved to the database, so using it in OpeningHours.objects.create(...) will give an error.


Restaurant


super(Restaurant, self).save(*args, **kwargs)


if not self.latlng


OpeningHours.objects.create(...)





super(Restaurant, self).save(*args, **kwargs) I get an syntax Error with the ".save(*args, **kwargs):
– A True Novice
Jul 2 at 15:33





I don't understand your comment.
– Alasdair
Jul 2 at 15:35





When I made the update and changed to super(Restaurant, self).save(*args, **kwargs), I'm getting a SyntaxError after ".save"
– A True Novice
Jul 2 at 15:36





I still don't understand your comment. I don't know what update you mean. If you have an error, please include the full traceback and the code that causes it in the question.
– Alasdair
Jul 2 at 15:39






def save(self, *args, **kwargs): was fine. Changing it to def super(Restaurant, self).save(*args, **kwargs) is completely wrong.
– Alasdair
Jul 2 at 15:43


def save(self, *args, **kwargs):


def super(Restaurant, self).save(*args, **kwargs)






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

fN7,m tBhlLIvorIzpYnj,yV2ApBlIrqOo5awFZOr5xjnhM0JMHYOOx1AdNoiqG,CG,qdwcxVO,3K5xRJ
mLOozfm454mFs0HPcRw58I,3krgE OFH 1Z9NXnYYUh Eb7y6rZ4teC L PcqXORkH,GhSB,qBSWS6

Popular posts from this blog

PHP contact form sending but not receiving emails

Do graphics cards have individual ID by which single devices can be distinguished?

Create weekly swift ios local notifications