Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Encoding in json response
I try to serialize several models into one response. def get_user(request): id = request.GET.get("id") user = User.objects.filter(id=id) userProfile = Profile.objects.filter(user_id=id) profilePic = ProfilePic.objects.filter(user_id=id) profileFields = ProfileFields.objects.filter(user_id=id) combined = list(chain(user, userProfile, profilePic, profileFields)) json = serializers.serialize('json', combined) return JsonResponse(json, safe=False) But in response I get strange response like this "[{\"model\": \"auth.user\", \"pk\": 19, \"fields\": {\"password\": \"pbkdf2_sha256$24000$6xE3MBbVd6tR$HkfAMTT/JLjcNNHV5BTaPDP0r6tqk/wzPdYMSCpTq3E=\", \"last_login\": null, \"is_superuser\": false, \"username\": \"Ivan89@mail.ru\", \"first_name\": \"\", \"last_name\": \"\", \"email\": \"Ivan89@mail.ru\", \"is_staff\": false, \"is_active\": true, \"date_joined\": \"2016-10-15T11:52:44.874Z\", \"groups\": [], \"user_permissions\": []}}, {\"model\": \"datingapp.profile\", \"pk\": 9, \"fields\": {\"user\": 19, \"gender\": \"MA\", \"name\": \"Ivan\", \"birthday\": \"1997-10-15\", \"weight\": 0, \"heigth\": 0, \"sign\": \"E\", \"orientation\": \"E\", \"bodytype\": \"E\", \"education\": \"E\", \"religion\": \"E\", \"smoking\": \"E\", \"alcohol\": \"E\", \"kids\": \"E\", \"pets\": \"E\", \"location\": \"Unknown\", \"latitude\": 0.0, \"longtitude\": 0.0}}, {\"model\": \"datingapp.profilepic\", \"pk\": 4, \"fields\": {\"user\": 19, \"profilePic\": \"Images/profilePic_DTFjDED.jpg\"}}, {\"model\": \"datingapp.profilefields\", \"pk\": 3, \"fields\": {\"user\": 19, \"title\": \"\u041a\u043e\u0440\u043e\u0442\u043a\u043e \u043e\u0431\u043e \u043c\u043d\u0435\", \"text\": \"\u041a\u043e\u0440\u043e\u0442\u043a\u0438\u0439 \u0440\u0430\u0441\u0441\u043a\u0430\u0437 \u043e \u0441\u0435\u0431\u0435 - \u0447\u0435\u043c \u044f \u0437\u0430\u043d\u0438\u043c\u0430\u044e\u0441\u044c \u043f\u043e \u0436\u0438\u0437\u043d\u0438, \u043e \u0447\u0435\u043c \u0434\u0443\u043c\u0430\u044e, \u0447\u0442\u043e \u0435\u043c, \u0447\u0442\u043e \u043f\u044c\u044e \u0438 \u0437\u0430\u0447\u0435\u043c\", \"order\": 1}}, {\"model\": \"datingapp.profilefields\", \"pk\": 4, \"fields\": {\"user\": 19, \"title\": \"\u0427\u0435\u043c \u044f \u0437\u0430\u043d\u044f\u0442 \u0432 \u0436\u0438\u0437\u043d\u0438\", \"text\": \"\u0417\u0430\u043d\u044f\u0442 \u0432\u0430\u0436\u043d\u044b\u043c\u0438 \u0434\u0435\u043b\u0430\u043c\u0438. \u0414\u0435\u043b\u0430\u0442\u044c, \u0434\u0435\u043b\u0430\u0442\u044c, \u0434\u0435\u043b\u0430\u0442\u044c. \u041d\u0443, \u043a\u043e\u0433\u0434\u0430 \u043d\u0430\u0441\u0442\u0440\u043e\u0435\u043d\u0438\u0435 \u0435\u0441\u0442\u044c.\", \"order\": 2}}, {\"model\": \"datingapp.profilefields\", \"pk\": 5, \"fields\": {\"user\": 19, \"title\": \"\u0427\u0442\u043e \u0443 \u043c\u0435\u043d\u044f \u043f\u043e\u043b\u0443\u0447\u0430\u0435\u0442\u0441\u044f \u043b\u0443\u0447\u0448\u0435 \u0432\u0441\u0435\u0433\u043e?\", … -
i am new at backbone.js. I am trying to print data in console log using model. But i am failing. I don't know. Also i am using django version 1.9
i am new at backbone.js. I am trying to print data in console log using model. But i am failing. I don't know. Also i am using django version 1.9. enter code here var student_read_data = new StudentModel({id:studnet_id}); console.log(student_read_data); console.log("-- --- --- -- -- -- --- "); console.log(student_read_data); student_read_data.fetch({ success: function () { console.log("Your Name is : "+ student_read_data.get(name)); } }); } }else { console.log("This is a test "); } } }); $(function () { var view = new StudentFilterView({ el: 'form', model: new StudentModel() }); }); -
Django upload of image fails after the first upload after server is booted up
I have a Django project which accepts image uploads via the REST Framework. The first time I upload an image from my app it works fine but all subsequent attempts to upload images fail. If I reboot the server it works for the first image upload and then fails for all subsequent uploads. Every time I reboot the server it works for just one upload. The error I am getting is: ValueError: The 'photo' attribute has no file associated with it. The full log looks like this: [16/Oct/2016 17:18:03] "POST /api/photoupload/ HTTP/1.1" 201 399 Internal Server Error: /api/photoupload/ Traceback (most recent call last): File "/Users/billnoble/Documents/YHistory-Server/yhistoryvenv/lib/python3.4/site-packages/django/core/handlers/base.py", line 149, in get_response response = self.process_exception_by_middleware(e, request) File "/Users/billnoble/Documents/YHistory-Server/yhistoryvenv/lib/python3.4/site-packages/django/core/handlers/base.py", line 147, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/billnoble/Documents/YHistory-Server/yhistoryvenv/lib/python3.4/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/Users/billnoble/Documents/YHistory-Server/yhistoryvenv/lib/python3.4/site-packages/rest_framework/viewsets.py", line 87, in view return self.dispatch(request, *args, **kwargs) File "/Users/billnoble/Documents/YHistory-Server/yhistoryvenv/lib/python3.4/site-packages/rest_framework/views.py", line 466, in dispatch response = self.handle_exception(exc) File "/Users/billnoble/Documents/YHistory-Server/yhistoryvenv/lib/python3.4/site-packages/rest_framework/views.py", line 463, in dispatch response = handler(request, *args, **kwargs) File "/Users/billnoble/Documents/YHistory-Server/yhistoryvenv/lib/python3.4/site-packages/rest_framework/mixins.py", line 21, in create self.perform_create(serializer) File "/Users/billnoble/Documents/YHistory-Server/items/views.py", line 379, in perform_create the_photo_url = the_photo.photo.url File "/Users/billnoble/Documents/YHistory-Server/yhistoryvenv/lib/python3.4/site-packages/django/db/models/fields/files.py", line 68, in _get_url self._require_file() File "/Users/billnoble/Documents/YHistory-Server/yhistoryvenv/lib/python3.4/site-packages/django/db/models/fields/files.py", line 46, in _require_file raise ValueError("The '%s' attribute has no file associated … -
Setting up a CDN with Wagtail CMS
I am looking into possibly setting up a CDN to use with my Wagtail sites. I am thinking that this will be a more efficient way to manage media uploads during stage/production pushes, since right now the media folder has to be manually copied from server to server on deploy. If all of the images were being accessed from a CDN then this wouldn't be an issue. This would be my first time using a CDN so I'm looking for advice. There is lots of info on using a CDN with WordPress, but not a lot of documentation on setting one up with Wagtail/Django. I have the following questions about it: Does anyone have any suggestions on the best way to implement the CDN with Wagtail? How does it handle the uploads that the user submits through the CMS? Most of the images will be uploaded as part of the static files, but how does it work when the user uploads a photo as part of a post? Which CDN companies have you had the best/worst experiences with? The sites I am planning to use this for are professional/business, but not e-commerce. Also, if there is a more efficient way … -
How can i display my data in database and export it to pdf -Django
my x variable is getting all the data in my database, i guess? someone help me how can i display all data and export it to pdf file. response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="WishList.pdf"' buffer = BytesIO() # Create the PDF object, using the BytesIO object as its "file." p = canvas.Canvas(buffer) x = Item.objects.all() p.drawString(100, 100,x) p.drawString(200,300,"sad") # Close the PDF object cleanly. p.showPage() p.save() # Get the value of the BytesIO buffer and write it to the response. pdf = buffer.getvalue() buffer.close() response.write(pdf) return response -
iterate list and use that value for dictionary key
My dictionary looks some think like this. allCurrencies = { 'AUD': ['Australian Dollar', 'au'], 'GBP': ['British Pound', 'gb'], 'CAD': ['Canadian Dollar', 'ca'], 'INR': ['Indian Rupee', 'in'], 'JPY': ['Japanese Yen', 'jp'], 'RUB': ['Russian Ruble', 'ru'], 'SGD': ['Singapore Dollar', 'sg'], 'CHF': ['Swiss Franc', 'ch'], 'USD': ['US Dollar', 'us'] } and my array contains this: commonCurrencies = ['USD', 'EUR', 'GBP', 'JPY'] My main goal is to iterate commonCurrencies and use it as a key for the dictionary allCurrencies. My django template currently look like this: <tr> {% for sym in commonCurrencies %} <td>{{allCurrencies.sym.0}}<td> {% endfor %} </tr> But it does not seem to work. What am I doing wrong. Thanks -
Meta.fields contains a field that isn't defined on this FilterSet: ****
I am using Django Filters package . I define my filter in following way in the view class UnitFilter(django_filters.FilterSet): class Meta: model = Unit fields = ['floor', 'number', 'building','lease','leaseterm','lease__is_active','lease__is_terminated','lease__is_renewed',] My Unit Model on which I filter is following class Unit(CommonInfo): version = IntegerVersionField( ) number = models.CharField(max_length=30,null=True, blank=True) max_occupants = models.PositiveSmallIntegerField() floor = models.PositiveSmallIntegerField() rooms = models.PositiveSmallIntegerField() is_disabled_access = models.BooleanField(default=False) balcony_quantity = models.PositiveSmallIntegerField() building = models.ForeignKey(Building) recomended_price = models.DecimalField(max_digits=7, decimal_places=2) _lease = None _leaseterm = None #check = models.ManyToManyField(UnitCheck, through='UnitChecklist') def _get_total(self): from conditions.models import LeaseTerm from lease.models import Lease lease_dict = Lease.objects.filter(unit_id=self.id, is_active = True , is_terminated = False).aggregate(Max('id')) if lease_dict['id__max']: lease = lease_dict['id__max'] else: lease = 0 leaseterm_dict = LeaseTerm.objects.filter(lease_id=lease, is_active = True , is_terminated = False).aggregate(Max('id')) if leaseterm_dict['id__max']: leaseterm = leaseterm_dict['id__max'] else: leaseterm = 0 self._lease = lease self._leaseterm = leaseterm @property def lease(self): if self._lease is None: self._get_total() return self._lease @property def leaseterm(self): if self._leaseterm is None: self._get_total() return self._leaseterm There is 2 calculated properties in this model lease and leaseterm lease property has no problem when leaseterm gives me this error Meta.fields contains a field that isn't defined on this FilterSet: leaseterm why? -
Login - next parameter doesn't work
I can't set next paremeter to login form in Django. The login is modal window. I tried to add ?next=... to form action and add a hidden input with name next and value some_url which doesn't work too. I want user to be forced to log in and then to be redirected to new_reservation url if they aren't logged in yet. Otherwise go to new_reservation straight. There are two problems. The first is that I use this modal everywhere in my page and when user clicks on login button, he can log in through this modal and redirected to homepage. But if this modal is shown because they clicked on new_reservation button, I want them to be redirected to new_reservation page after log in. This is login button in base.html: <li> <a class="signup cursorhand" id="loginbutton" data-toggle="modal" data-target="#loginModal">{% trans "Sign in" %}</a> </li> And this is new_reservation button: {% if user.is_authenticated %} <a class="signup col-sm-2 col-sm-offset-5 text-center" href="{% url "new_reservation" %}"> {% trans "Make a reservation" %} </a> {% else %} <a class="signup col-sm-2 col-sm-offset-5 text-center cursorhand" data-toggle="modal" data-target="#loginModal"> {% trans "Make a reservation" %} </a> {% endif %} This is the modal which is in base.html: <!-- Modal --> <div … -
Error when using heroku-toolbelt: 3.43.12 on windows 7, cant run any command
Whenever I run any command it gives me the following error panic: mkdir U:: The specified network name is no longer available. goroutine 1 [running]: panic(0x67d400, 0x12ab2800) /usr/local/go/src/runtime/panic.go:500 +0x331 main.must(0x7be130, 0x12ab2800) /home/ubuntu/.go_workspace/src/github.com/heroku/cli/io.go:189 +0x44 main.configHome(0x0, 0x0) /home/ubuntu/.go_workspace/src/github.com/heroku/cli/filesystem.go:66 +0 x157 main.init() /home/ubuntu/.go_workspace/src/github.com/heroku/cli/filesystem.go:27 +0 x2c6 panic: mkdir U:: The specified network name is no longer available. goroutine 1 [running]: panic(0x67d400, 0x12cb2800) /usr/local/go/src/runtime/panic.go:500 +0x331 main.must(0x7be130, 0x12cb2800) /home/ubuntu/.go_workspace/src/github.com/heroku/cli/io.go:189 +0x44 main.configHome(0x0, 0x0) /home/ubuntu/.go_workspace/src/github.com/heroku/cli/filesystem.go:66 +0 x157 main.init() /home/ubuntu/.go_workspace/src/github.com/heroku/cli/filesystem.go:27 +0 x2c6 panic: mkdir U:: The specified network name is no longer available. goroutine 1 [running]: panic(0x67d400, 0x12c527e0) /usr/local/go/src/runtime/panic.go:500 +0x331 main.must(0x7be130, 0x12c527e0) /home/ubuntu/.go_workspace/src/github.com/heroku/cli/io.go:189 +0x44 main.configHome(0x0, 0x0) /home/ubuntu/.go_workspace/src/github.com/heroku/cli/filesystem.go:66 +0 x157 main.init() /home/ubuntu/.go_workspace/src/github.com/heroku/cli/filesystem.go:27 +0 x2c6 ! error getting commands pid 18844 exit 2 I dont get it, I downloaded the windows toolbet, why is this using addresses of ubuntu, I even uninstalled it and reinstalled it again.... -
Adding a new Unique Field in an existing database table with existing values- Django1.7/MySql
I have an existing database table. I want to add a new (Char)field to it. This field will have unique values. When I try to do so: id = models.CharField(max_length=100, Unique=True) I get integrity error. Some of the other things I have tried : id = models.CharField(max_length=100, Unique=True, default="".join([random.random(), random.random()]))) id = models.CharField(max_length=100, default="".join([random.random(), random.random()]))) Same error. Is there a way around this? -
Django - trouble with separating objects by user and date
So I have these models: excercises_choices = (('Bench Press', 'Bench press'),('Overhead Press', 'Overhead Press'), ('Squat', 'Squat'), ('Deadlift', 'Deadlift')) unit_choices = (('kg','kg'), ('lbs', 'lbs')) class Lifts(models.Model): user = models.ForeignKey('auth.User', null=True) excercises = models.CharField(max_length=200, choices=excercises_choices) sets = models.IntegerField(null=True, blank=True) reps = models.IntegerField(null=True, blank=True) weight = models.FloatField() unit = models.CharField(max_length=3, choices=unit_choices) created_date = models.ForeignKey('Dates') amrap_set = models.BooleanField(default=False) amrap_rep = models.IntegerField(null=True, blank=True) def __str__(self): return self.excercises class Dates(models.Model): created_date = models.DateField(unique=True) def __str__(self): return str(self.created_date) Let's say I have few lifts at different dates for admin and few lifts at different for xx user. I want multiple lifts matching one date that's why I've made foreign key. (eg. 3 lifts to 2016-10-10 and 2 lifts to 2016-10-11). Here is a view for showing it: @login_required def entries(request): date = Dates.objects.all().order_by('-created_date') lifts_by_user = Lifts.objects.filter(user=request.user) return render(request, 'lift/entries.html', {'date': date, 'lifts_by_user': lifts_by_user}) And template: {% extends 'lift/base.html' %} {% block content %} {{ user }} {% if user.is_authenticated %} {% for date in date %} <p><strong><a href="{% url 'lift_date' pk=date.pk %}">{{ date }}</a></strong> {% for i in date.lifts_set.all %} {{ i }} {% endfor %} <a href="{% url 'new_lifts' %}">add new lift</a></p> {% endfor %} {% endif %} <p> <a href="{% url 'entries_delete' %}">Delete lifts or … -
Django dateutil parse is changing the date to today's date
I am trying to use Django dateutil.pareser.parse() to change the date '2016:09:24 17:08:45' to '2016-09-24 17:08:45'. But when I use the following code: the_timestamp = self.request.query_params.get('timestamp',0) # = '2016:09:24 17:08:45' the_parsed_timestamp = dateutil.parser.parse(the_timestamp) I get the result the_parsed_timestamp = '2016-10-16 17:08:45'. 2016-10-16 is today's date. Why is dateutil.parser.parse replacing the date with today's date (and leaving the time part alone)? -
Best Way to launch an asynchronous function in django?
I am using tweepy library to collect tweets from twitter streaming API and store them in an Elasticsearch server. Overall I am writing a simple Django application to display the tweets in real time, over a map. However for that I need the ElasticSearch database to be populated in realtime, constantly by the Django Server i.e it should preferably start doing it as soon as the Django Server is launched. What will be a good way to go about it ? The calls look as followin: streamer = tweepy.Stream(twitter_api.auth, listener=stream_listener) streamer.filter(locations=[-180, -90, 180, 90], languages=['en'], async=True) -
Django, calendar widget doesn't work with ModelForm and Form Media
I found one blog. It explains how apply calendar widget with form media. It is what I exactly want to make. so I followed instructions. but js and css files doesn't work in widget. I tried to figure out this problem. I spent quite much time by searching and reading stuffs. But I can't get what's wrong in my situation exactly. Well, It could be very easy question but I will appreciate if you can give me any hint to figure out this! model.py class Birthday(models.Model): birthday = models.DateField(null=True) views.py def register_birthday(request): if request.method == 'POST': form = BirthdayForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/success') else: form = BirthdayForm() return render(request, 'sale/registerbirthday.html', {'form':form}) forms.py class DateUIWidget(forms.TextInput): def _media(self): return forms.Media(css = { "all": ("tiny-date-picker.css",) }, js = ("tiny-date-picker.js", "date-init.js",)) media = property(_media) class BirthdayForm(forms.ModelForm): class Meta: model = Birthday fields = ('birthday',) widgets = { "birthday" : DateUIWidget(attrs={'class':'dateuiwidget', 'id':'id_birthday'}), } actually I wrote at first like below. but I changed to check if it works when I use media as a dynamic property. class DateUIWidget(forms.TextInput): class Media: css = { "all": ("tiny-date-picker.css",) } js = ("tiny-date-picker.js", "date-init.js",) forms.py first <form action="." method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit"> </form> … -
Url argument with Django
I' having some problem with url in Django (1.9) Tried many way to solve it, but still the same type of error Reverse for 'elus' with arguments '()' and keyword arguments '{u'council': u'CFVU'}' not found. 1 pattern(s) tried: ['elus/(?P<council>[A-B]+)$'] The actual code is this : View : class RepresentativeView(ListView): model = Representative template_name= 'lea/elus.html' context_object_name = 'represents' def get_queryset(self, council): return Representative.objects.filter(active=True).filter(council=council).order_by(order) url : url(r'^elus/(?P<council>[A-B]+)$', views.RepresentativeView.as_view(), name='elus'), Template : {% url 'elus' council='CFVU' %} I've tried with **kwargs and other things. It work with **kwargs in another function with in url, and my query is based on the id. But here, with a string I don't find the solution. Thanks for you help -
I am taking Selenium error
Using 1 seconds of delay Traceback (most recent call last): File "instaBrute.py", line 142, in <module> main() File "instaBrute.py", line 136, in main driver = webdriver.Firefox(profile) File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/firefox/webdriver.py", line 135, in __init__ self.service.start() File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/common/service.py", line 71, in start os.path.basename(self.path), self.start_error_message) selenium.common.exceptions.WebDriverException: Message: 'geckodriver' executable needs to be in PATH. Exception AttributeError: "'Service' object has no attribute 'process'" in <bound method Service.__del__ of <selenium.webdriver.firefox.service.Service object at 0x7f1aaba35110>> ignored I am using Last Version of Kali Linux , and when I want to use program which using selenium , I take this error . So I try "pip uninstall selenium " - "pip install selenium " again , and nothing changes . Thanks for helps -
Show values from another model in the form template for one model
I have a model called Stock. I have another model called Pipeline. Both models have similar fields. So, basically they both contain same type of data. I have a form for updating the stock. I want to list values from the Pipeline model for each field of the Stock model. Please help. Here is my form template which is rendering the field from the Stock model form. {% for field in form %} <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <span class="text-danger small">{{ field.errors }}</span> </div> <label class="control-label col-sm-6 col-md-6 col-lg-6" for="{{ field.html_name }}">{{ field.label_tag }}</label> <div class="col-sm-6 col-md-6 col-lg-6">{{ field }}</div> </div> {% endfor %} -
Django models: database design for user and follower
In Django model I am making a table 'followers', which has: user's id. (this is followed by) user's id (this is follower) that's simple a user can follow other users. How should I define the model in Django? I tried this, but does not work: user = models.ForeignKey('self') follower_id = models.ForeignKey('self') How should this be done? thanks -
How to build a test excecution system in python? [on hold]
we use pytest and requests to do api automation test, This does work well. But now director want to see the test result in web and given us a lot of requirements. store test scripts in file or db store test data in db can edit test data and test script in web can add test case based on test script(keyword!) in web test report in web(running and after running) can set dns for each test case test suite can include many test cases. test suite can include many test suites. showing test cases and test suites in navigation tree searching test cases Modifying many test cases at the same time. Running test cases schedulely Have anyone some similar system? I only found: And Django based full-featured test case management system http://nitrate.readthedocs.org/ We want to use PostgreSQL or mysql 、django and activemq、celery or thrift. Hope could see your advices, Thanks! -
Django model form does not appear in Django Admin (Only server)
I'm using Django 1.8. I have a strange problem. My Student Model page in Django Admin has no attribute! Screenshot from Django Admin page for a sample Student model I just check read_only fields and form and they were correct. (I logged in with super user account) Models.py class Student(models.Model): primary_member = models.OneToOneField(Member, related_name='student') phone_number = models.CharField(max_length=13, blank=True, null=True) certificate_deadline = models.DateField(blank=True, null=True) primary_moshaver = models.ForeignKey(Moshaver, blank=True, null=True, related_name='students') target_rank = models.IntegerField(default=100) sub_field_set = models.BooleanField(default=False) national_id = models.CharField(max_length=10, blank=True, null=True) city = models.ForeignKey(City, blank=True, null=True, related_name='livings') organization = models.ForeignKey(Organization, blank=True, null=True, related_name='memebrsOf') gender = models.BooleanField(default=True, blank=True) # True is Male False is Female primary_moaref = models.ForeignKey(Moshaver, blank=True, null=True, related_name='subStudents') def __str__(self): return "{} {}".format(self.primary_member.first_name, self.primary_member.last_name) def get_sub_field(self): if self.sub_field_set: return self.main_course.all()[0].ref_courseSubField.primary_subField return None Admin.py class StudentForm(forms.ModelForm): class Meta: model = Student fields = '__all__' class StudentAdmin(admin.ModelAdmin): search_fields = ( 'primary_member__first_name', 'primary_member__last_name', 'primary_member__primary_user__username', 'primary_member__primary_id') inlines = (StudentMainCourseInline,) form = StudentForm list_display = ('id', 'primary_member', 'certificate_deadline', 'member_id') list_editable = ('certificate_deadline',) def member_id(self, obj): return obj.primary_member.primary_id Oh by the way i don't have this problem on my local! Only on server!!!! -
What is proper workflow for insuring "transactional procedures" in case of exceptions
In programming web applications, Django in particular, sometimes we have a set of actions that must all succeed or all fail (in order to insure a predictable state of some sort). Now obviously, when we are working with the database, we can use transactions. But in some circumstances, these (all or nothing) constraints are needed outside of a database context (e.g. If payment is a success, we must send the product activation code or else risk customer complaints, etc) But lets say on some fateful day, the send_code() function just failed time and again due to some temporary network error (that lasted for 1+ hours) Should I log the error, and manually fix the problem, e.g. send the mail manually Should I set up some kind of work queue, where when things fail, they just go back onto the end of the queue for future retry? What if the logging/queueing systems also fail? (am I worrying too much at this point?) -
Use custom model from legacy database to authenticate login django
Probably a very basic question. How can i use my own legacy db table for authenticating login of the users in Django? All the methods i am finding seem really confusing. I want to use Django's own authentication system with modification of 'Persons' database table instead of 'User'. -
How to create factory boy with several child
I have two django model like class Country(models.Model): country_name = models.CharField(max_length=10) class Resident(models.Model): country = models.ForeignKey('Country') name = models.CharField(max_length=10) age = models.PositiveSmallInteger() and I want to factory boy create like a country with two child which has different attribute. For example, somefactory.create() makes FooCountry and FooCountry has two resident. name=Paul, country=foo, age=33 name=Jamse, country=foo, age=34 How to do it? -
ValueError at /api/loanextension/add/ Cannot assign "<SimpleLazyObject: <User: biju>>": "LoanExtension.owner" must be a "LoanApplication" instance
class LoanApplication(models.Model): user = models.ForeignKey(User, related_name="loan_user", **optional) profile = models.ForeignKey(Profile, related_name='profile_user') amount = models.DecimalField(_('Amount') ,max_digits=5, default=30000, decimal_places=0, help_text='Please fill the amount required') period = models.PositiveIntegerField(_('Days') ,default=30, help_text='Please fill the repayment time required') timestamp = models.DateField(_('Date') , default=datetime.date.today, help_text='Date of Application') status = models.CharField(choices=STATUS_CHOICES, max_length=20, default='1') is_approved = models.BooleanField(default=False) def __str__(self): return str(self.user) class LoanExtension(models.Model): owner = models.ForeignKey(LoanApplication) new_tenure = models.PositiveIntegerField(_('Days'), default=30, help_text='Please fill the repayment time required') new_loan_amount = models.DecimalField(max_digits=5, default=30000, decimal_places=0, help_text='Please fill the amount required') datestamp = models.DateField(default=datetime.date.today) interest = models.DecimalField(max_digits=5, default=30000, decimal_places=0) extension_fee = models.DecimalField(max_digits=5, default=30000, decimal_places=0) is_approved = models.BooleanField(default=False) def __str__(self): return str(self.owner) class LoanExtensionSerializer(serializers.ModelSerializer): class Meta: model = LoanExtension fields = ['id', 'new_tenure', 'new_loan_amount', 'interest', 'extension_fee', 'datestamp', 'owner' ] I want to assign the loan extension to loan application which is connected by a foreign key, when I am adding it throws the value error, please give me some help to solve it. Is this way of foreign key is a right way or should I provide user as foreign key, please suggest, Thank you. -
DRF - nested serializer
I have several models class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) gender = models.CharField(max_length=2) name = models.CharField(max_length=200) birthday = models.DateField(auto_now=False, auto_now_add=False) weight = models.IntegerField(default=0) heigth = models.IntegerField(default=0) sign = models.CharField(max_length=200, choices=SIGNS_CHOICES, default='E') orientation = models.CharField(max_length=200, choices=ORIENTATION_CHOICES, default='E') bodytype = models.CharField(max_length=200, choices=BODYTYPE_CHOICES, default='E') education = models.CharField(max_length=200, choices=EDUCATION_CHOICES, default='E') religion = models.CharField(max_length=200, choices=RELIGION_CHOICES, default='E') smoking = models.CharField(max_length=200, choices=SMOKING_CHOICES, default='E') alcohol = models.CharField(max_length=200, choices=ALCOHOL_CHOICES, default='E') kids = models.CharField(max_length=200, choices=KIDS_CHOICES, default='E') pets = models.CharField(max_length=200, choices=KIDS_CHOICES, default='E') location = models.CharField(max_length=100) latitude = models.FloatField() longtitude = models.FloatField() class ProfilePic(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profilePic = models.ImageField(upload_to='Images/', default='Images/None/No-img.jpg') class ProfileFields(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() order = models.IntegerField(default=0) and several serizlizers class ProfilePicSerializer(ModelSerializer): class Meta: model = ProfilePic fields = [ 'profilePic', 'user', ] class ProfileSerializer(ModelSerializer): class Meta: model = Profile fields = '__all__' class ProfileFieldsSerializer(ModelSerializer): class Meta: model = ProfileFields fields = [ 'user', 'title', 'text', 'order' ] What I try to do is to create user serizlizer that will show profile, profilePic and profileFields I do it like so class UserSerializer(ModelSerializer): profile = ProfileSerializer(many=False) profilePic = ProfilePicSerializer(many=False) profile_fields = ProfileFieldsSerializer(many=True) class Meta: model = User fields = '__all__' write_only_fields = ('password',) read_only_fields = ('id',) def create(self, validated_data): user = User.objects.create( username=validated_data['username'], …