Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is wrong with this? ['ManagementForm-Daten fehlen oder wurden manipuliert.']
I get this error: ['ManagementForm-Daten fehlen oder wurden manipuliert.'] This is my model: from django.db import models from daytrips.models import Trip class Buchungen(models.Model): PERSONEN_CHOICES = [(i, str(i)) for i in range(1,10)] reiseziel = models.CharField(max_length=50) datum_abfahrt = models.CharField(max_length=50) vorname = models.CharField(max_length=50) nachname = models.CharField(max_length=50) adresse = models.CharField(max_length=50) plz = models.CharField(max_length=20) stadt = models.CharField(max_length=50) email = models.EmailField() telefon = models.CharField(max_length=50) geburtsdatum = models.CharField(max_length=200) personen = models.IntegerField( choices=PERSONEN_CHOICES, default=0) preis = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) gesamt = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) created = models.DateTimeField(auto_now_add=True) updated = models.DateField(auto_now=True) class Meta: ordering = ('-created',) verbose_name = 'Buchung' verbose_name_plural = 'Buchungen' def __str__(self): return self.vorname def save(self, *args, **kwargs): self.gesamt = self.preis * self.personen super(Buchungen, self).save(*args, **kwargs,) class Mitreisende(models.Model): buchung = models.ForeignKey(Buchungen, related_name='items', on_delete=models.CASCADE) reiseziel = models.ForeignKey(Trip, related_name='order_items', on_delete=models.CASCADE) vorname = models.CharField(max_length=50) nachname = models.CharField(max_length=50) geburtsdatum = models.CharField(max_length=200) In my forms.py i have: from django import forms from django.forms import HiddenInput from django.forms import modelformset_factory from .models import Buchungen, Mitreisende class BuchungForm(forms.ModelForm): class Meta: model = Buchungen fields = [ 'reiseziel', 'datum_abfahrt', 'vorname', 'nachname', 'adresse', 'plz', 'stadt', 'email', 'telefon', 'geburtsdatum', 'preis', 'personen', 'gesamt', ] widgets = { 'personen': forms.Select, } reiseziel = forms.CharField(widget=forms.TextInput(attrs={'reiseziel': 'reiseziel', 'readonly': 'readonly'})) datum_abfahrt = forms.CharField(widget=forms.TextInput(attrs={'datum_abfahrt': 'datum_abfahrt', 'readonly': 'readonly'})) MitreisendeModelFormset = modelformset_factory( Mitreisende, fields = … -
why django development server act like single thread while the docs "The server is multithreaded by default."-- version 2.1
I am a beginner of Django web framework, and I'm using Django 2.1.2. Now I encountered one question, does Django run in single thread or multithreads ?I checked the docs and it says 'the server is multithreaded by default.' while i have tested in my local env, it act just like single-thread. my view functions is: class Hello(APIView): """ for testing django single-threading """ def get(self, request): print("enter in the view") time.sleep(10) print("finished...") return HttpResponse("finished!") I run Django application in terminal by: python manage.py runserver I requested the url twice at nearly the same time, and the reponse is: enter in the view finished... [13/Jan/2019 10:43:50] "GET /account/hello HTTP/1.1" 200 9 enter in the view finished... [13/Jan/2019 10:44:00] "GET /account/hello HTTP/1.1" 200 9 It handled requests just like in single-thread way, did I do something wrong or I understand in wrong, thanks for help. -
add a png image to an existing pdf in django
I am trying to add a .png file in an existing pdf. I got an example,i edited the position of .png in pdf to place it in left-bottom corner. But it is creating new pdf. I tried to go through reportlab's documentation to get any hits but failed. What should i do to achieve the desired result? I want to achieve it though any 3rd party python package or related to python code not using photoshp or adobe acrobat. def PrintImage(request): response = HttpResponse(content_type='application/pdf') doc = SimpleDocTemplate(response,rightMargin=600, leftMargin=0, topMargin=150, bottomMargin=18) doc.pagesize = landscape(A4) elements = [] I = Image('static/images/account.png') I.drawHeight = 1.0*inch I.drawWidth = 1.0*inch elements.append(I) doc.build(elements) return response -
How can I access certain table rows in a for loop?
I wan't to highlight only the contacts of a company they're related to in my table body. At the moment I'm only able to highlight all of the contacts regardless of which company's contacts they are. I don't think I can use find() method since the contact row is different from he company row. tbody {% for company in company_list %} <tr class="company-row"> <th class="company-name" scope="row">{{ company.name }}</th> <td>{{ company.order_count }}</td> <td class="order-sum">{{ company.order_sum|floatformat:2 }}</td> <td class="text-center"><input type="checkbox" name="select{{company.pk}}" id=""></td> </tr> {% for contact in company.contacts.all %} <tr class="contact-row"> <td>{{ contact.first_name }} {{ contact.last_name }}</td> <td class="contact-orders">Orders: {{ contact.order_count }}</td> <th>&nbsp;</th> <td></td> </tr> {% endfor %} {% endfor %} script $(document).ready(function() { $(".company-row").hover(function() { sum = $(this).find(".order-sum").html() // get value of total sales if (sum > 50000) { $(this).addClass("company-row-over") // green $(".contact-row").each(function() { orders = $(this).find(".contact-orders").html() // get orders from each contact orders = orders.split(':') orders = orders[1] orders = parseInt(orders) if (orders > 3) { $(this).addClass("contacts") // yellow } }) } else { $(this).addClass("company-row-under") // orange } }, // clear highlighting on mouse out function() { $(this).removeClass() $("table tr#contact-row").removeClass() }) }) -
sorl-thumbnail creating urls that don't correspond to files
I have sorl-thumbnail configured correctly, as far as I can tell, and it seems to generate URLS to thumbnails it creates, but I can't actually find the files it creates anywhere on my system. Relevant sections from my settings.py: STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': 'unix:/home/username/memcached.sock', } } So, in the result HTML, sorl-thumbnail generates links like this: mysite.com/media/cache/5c/fb/5cfb25bca62f90d9492e162b2e8b3a57.jpg When I search 5cfb25bca62f90d9492e162b2e8b3a57.jpg on my system, it is nowhere to be found. I have DEBUG and THUMBNAIL_DEBUG both set to true and have logging setup, and as far as I can tell no errors are being thrown. How can I troubleshoot this? -
Django + non-form buttons: How to connect a non-form button or link to django's python code in views.py?
How do I connect a non-form button or link, written in HTML, to python code in Django? Specifically, suppose I have a button in HTML that redirects the page using href="/some-link". How do I, say, save specific info to a session (i.e., save which button was pushed) in Django when such a button is pushed? Basically, I want to do something similar to the following in views.py: if request.POST['form-type'] == u"purchase-button": # save some info before redirecting the page request.session['some-variable'] = 'the-purchase-button-was-pressed' return redirect('some-link') ... except this isn't a form, so I can't actually do that. Do I modify the following HTML somehow? <a href="/some-link">Purchase</a> I'm a bit new to Django and web development in general, so any help will be much appreciated. (Basically, I have the exact question that was posted here in the following link, but I wasn't really satisfied with the answer: Django: How to trigger a session 'save' of form data when clicking a non-submit link ) -
['ManagementForm data is missing or has been tampered with']
I want to iterate item object and formset at the same time so i do this {% csrf_token %} {% for item, form in zipped %} {{ form.management_form }} <tr> <td> {{ item.name }} </td> <td> <p id="stock-{{ item.id }}" style="display:table-cell; vertical-align: middle;"> {{ item.stock }} </p> </td> <td> {{ form.action }} </td> <td> {{ form.qty }} </td> <td> {{ form.desc }} </td> </tr> {% endfor %} But when i submit it give me an error ['ManagementForm data is missing or has been tampered with'] For passing data i'm using built in python function zip() @login_required def Produk_Detail(request, p_id): product = Product.objects.get(id=p_id) items = product.item_set.all() formset = modelformset_factory(Log, fields=('action', 'qty', 'desc'), extra=items.count()) if request.method == 'POST': form = formset(request.POST) if form.is_valid(): instances = form.save(commit=False) zipped = zip(items, instances) for item, instance in zipped: instance.user = request.user instance.product = product instance.item = item instances = form.save() messages.success(request, 'Produk sukses diubah!') return redirect('gudang-produk-detail-test') else: messages.warning(request, 'Produk gagal diubah!') return redirect('gudang-produk-detail-test') else: form = formset(queryset=Log.objects.none(), initial = [{'action' : Action.objects.first()} for x in items]) zipped = zip(items, form) context = { 'title':'Gudang', 'product':product, 'items':items, 'forms':form, 'zipped':zipped } return render(request, 'Gudang/product_detail.html', context) So how to fix this, and also i'm a novice programmer. I … -
django model foreign key Accessing attributes of both models
products = Clothing.objects.select_related('product') for product in products: print(product.category+" "+product.price) print(product.category+" "+product.price) AttributeError: 'Clothing' object has no attribute 'price' [13/Jan/2019 13:31:53] "GET /mens_product/ HTTP/1.1" 500 65348 -
Making a car available or not-available in the form when a user books it for a period of time in Django
I am creating a car reservation system. The user books one car for a certain period of time. I have a Vehicle model that stores info specific to all vehicles. A Profile model that is extended from Django User model, a Booking model to handle the booking form, a Finished_bookings model that gets the Booking_id from Booking model when the booking period gets over. Part of my models.py file: models.py from django.contrib.auth.models import User class Vehicles(models.Model): car_no = models.CharField (max_length = 20, primary_key=True) photo = models.ImageField (upload_to ='images/vehicles') car_model = models.ForeignKey (Car_model, on_delete=models.CASCADE) yard = models.ForeignKey (Yard, on_delete=models.CASCADE) car_category = models.ForeignKey (Category, on_delete=models.CASCADE) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_pic = models.ImageField (upload_to ='images/profiles') mobile = models.IntegerField(blank=False) city = models.CharField (max_length = 20, blank=False) building_no = models.CharField (max_length = 15, blank=False) state = models.CharField (max_length = 15, blank=False) zip = models.IntegerField (blank=False) country = models.CharField (max_length = 20, blank=False) sex = models.CharField (max_length=12, blank=True) class Booking(models.Model): user = models.ManyToManyField(User) vehicles = models.ForeignKey(Vehicles, on_delete=models.CASCADE) date_from = models.DateField(auto_now=False,auto_now_add=False,blank=False) date_to = models.DateField(auto_now=False, auto_now_add=False, blank=False) pickup_from = models.CharField (max_length=20, blank=False) destination = models.CharField (max_length = 20, blank=False) booking_time = models.TimeField (auto_now=True, auto_now_add=True) class Finished_bookings(models.Model): status = models.CharField(max_length=10, NULL=True) # pending and finished bookings = … -
How add link to profile? Django 2.15
I have url, but it work with error. For example, link must be example/profile/3, but template redirects to example/profile/4. Profile create with signals. Pls help me. models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=30, blank=True, default='') last_name = models.CharField(max_length=30, blank=True, default='') location = models.CharField(max_length=30, blank=True, default='') #other fields def get_absolute_url(self): return reverse('profile-detail', args=[str(self.id)]) def __str__(self): return self.user.username class Post(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) #other fields def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) signals.py @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() admin.py class ProfileAdmin(admin.ModelAdmin): list_display = ('user', 'first_name', 'last_name', 'location', 'about_me', 'contacts') admin.site.register(Profile, ProfileAdmin) views.py class PostCreateView(FormView): form_class = PostForm template_name = 'post/post_form.html' success_url = reverse_lazy('posts') def form_valid(self, form): response = super(PostCreateView, self).form_valid(form) form.instance.user = self.request.user form.save() return response class PostDetailView(generic.DetailView): model = Post current urls.py url(r'^profile/(?P<pk>\d+)$', views.ProfileDetailView.as_view(), name='profile-detail'), post_detail.html {% extends "base_generic.html" %} {% block content %} <p><strong>Author:</strong> <a href="{% url 'profile-detail' post.user.pk %}">{{ post.user }}</a></p> <p><strong>Description:</strong></p> <p>{{ post.body|safe }}</p> ... -
Failing to lookup a field with a foreign key subfield in Django Rest Framework
I am using the django framework to serialize a django object. I have a profile model and the first field in the model is a foreignkey of the user object. I want to be able to pass a usename is the url patters for the profile. In the Views, I want to be able to take that username and go through the user foreignkey and find the profile with that username user. THis is what I have right now in my code: Views.py class ProfileListView(ListAPIView): query_set = Profile.objects.all() serializer_class = ProfileSerializer class ProfileDetailView(RetrieveAPIView): query_set = Profile.objects.all() serializer_class = ProfileSerializer lookup_field = 'user__username' urls.py path('profile/', ProfileListView.as_view()), path('profile/<username>', ProfileDetailView.as_view()), serializers.py class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ('user', 'gender', 'phone', 'ip_address', 'dob_month', 'dob_day', 'dob_year', 'address_street', 'address_city', 'address_state', 'address_postal', 'address_country', 'profile_pic', 'role') models.py class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) gender = models.CharField(max_length=12, choices=GENDER_CHOICES) # entity type phone = models.CharField(max_length=22) ip_address = models.CharField(max_length=32) dob_month = models.CharField(max_length=22, choices=MONTH_CHOICES) dob_day = models.SmallIntegerField() dob_year = models.SmallIntegerField() address_street = models.CharField(max_length=140) address_city = models.CharField(max_length=22) address_state = USStateField() address_postal = models.IntegerField() address_country = models.CharField(max_length=22) profile_pic = models.ImageField(upload_to='profile_pics/') role = models.CharField(max_length=12, choices=ROLE_CHOICES) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.user.username + ' - ' + self.type -
wagtail pathoverflow on adding new child page
I have developed a wagtail site and that works just fine. It's just a simple blog. I was able to add a blog index page and blog posts under them. Hover recently when try to add a new page it gives the error PathOverflow at /admin/pages/add/blog/blogpage/8/ Bellow is the complete traceback. Environment: Request Method: POST Request URL: https://vikatakavi.info/admin/pages/add/blog/blogpage/8/ Django Version: 2.1.5 Python Version: 3.5.2 Installed Applications: ['home', 'search', 'wagtail.contrib.forms', 'wagtail.contrib.redirects', 'wagtail.embeds', 'wagtail.sites', 'wagtail.users', 'wagtail.snippets', 'wagtail.documents', 'wagtail.images', 'wagtail.search', 'wagtail.admin', 'wagtail.core', 'modelcluster', 'taggit', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sitemaps', 'blog'] Installed Middleware: ['django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', 'wagtail.core.middleware.SiteMiddleware', 'wagtail.contrib.redirects.middleware.RedirectMiddleware'] Traceback: File "/home/ubuntu/projects/blogger/env/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/ubuntu/projects/blogger/env/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "/home/ubuntu/projects/blogger/env/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/ubuntu/projects/blogger/env/lib/python3.5/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 44. response = view_func(request, *args, **kwargs) File "/home/ubuntu/projects/blogger/env/lib/python3.5/site-packages/wagtail/admin/urls/__init__.py" in wrapper 102. return view_func(request, *args, **kwargs) File "/home/ubuntu/projects/blogger/env/lib/python3.5/site-packages/wagtail/admin/decorators.py" in decorated_view 34. return view_func(request, *args, **kwargs) File "/home/ubuntu/projects/blogger/env/lib/python3.5/site-packages/wagtail/admin/views/pages.py" in create 224. parent_page.add_child(instance=page) File "/home/ubuntu/projects/blogger/env/lib/python3.5/site-packages/treebeard/mp_tree.py" in add_child 1013. return MP_AddChildHandler(self, **kwargs).process() File "/home/ubuntu/projects/blogger/env/lib/python3.5/site-packages/treebeard/mp_tree.py" in process 387. newobj.path = self.node.get_last_child()._inc_path() File "/home/ubuntu/projects/blogger/env/lib/python3.5/site-packages/treebeard/mp_tree.py" in _inc_path 1114. raise PathOverflow(_("Path Overflow from: '%s'" % (self.path, ))) Exception Type: PathOverflow at /admin/pages/add/blog/blogpage/8/ Exception Value: Path Overflow … -
django library inline editing of records example from mozilla
MDN has this django tutorial of a library database webpage. I am attempting this section example and it worked. The goal here is when you see each author you can also see a list of their books in your library. This is their github page. I was able to make the author page list their respective books. Now I want to challenge myself a bit further by making the author page list all the book instances as well. So before, if I go to an author like JK Rowling, I would be able to see Harry Potter 1, 2, and 3 (these are the three that I have added to my database). Now, I want to make it so that not only will I see these 3 books, I will also see each instance of the 3 books. So if I have two copies of Harry Potter 1, I will see these 2 entries instead. Here is what I have done to attempt it. I have added the class BooksInstanceInLine similar to how I did the class BooksInline, and I need a key between books instance to author as well. In class AuthorAdmin in admin.py I have added the following: … -
How to migrate default user data to custom user model in Django
As I want to customize Django user model, I migrated from default user model to my own custom user model. Since my Django project has been working since a long time ago, I need to keep the existing user data. I was thinking to move them manually, but Django default user model's passwords are hidden. How can I safely move existing user data to my custom user model? -
Case insensitive username in Django signup form
Here is my signup form, class SignupForm(forms.ModelForm): class Meta: model = User fields = ['first_name', 'last_name','username', 'email', 'password'] def clean_username(self): username = self.cleaned_data.get('username') email = self.cleaned_data.get('email') if username and User.objects.filter(username=username).exclude(email=email).count(): raise forms.ValidationError('This username has already been taken!') return username This works well to check if there is same username presents or not. However it does not check for case insensitivity. If there is a username e.g. 'userone', then it also accepts a username with 'Userone'. Although it does not break any functionality, but looks very unprofessional. My question is how can I check for case insensitive right in the forms, and raise error? -
Django form is not workin properly
i am trying to save data by form into 'ModuleNames' table but it is updating 'ModuleType' column of foreign(instance) table. I created an instance of foreign table because it was giving different error about assigning value to foreign key column and i learned instance is needed from blogs but it seems, it is not correct way. Could you please help me what is wrong with my code? models.py class ModuleTypes(models.Model): ModuleType = models.CharField(max_length = 50) ModuleDesc = models.CharField(max_length = 256) Sort = models.SmallIntegerField() isActive = models.BooleanField() slug = models.SlugField(('Type'), max_length=50, blank=True) class Meta: app_label = 'zz' def save(self, *args, **kwargs): if not self.id: self.slug = slugify(self.Type) super(ModuleTypes, self).save(*args, **kwargs) class ModuleNames(models.Model): ModuleName = models.CharField(max_length = 50) ModuleDesc = models.CharField(max_length = 256) ModuleSort = models.SmallIntegerField() isActive = models.BooleanField() ModuleType = models.ForeignKey(ModuleTypes, on_delete=models.CASCADE, null = True) slug = models.SlugField(('ModuleName'), max_length=50, blank=True) class Meta: app_label = 'zz' def __unicode__(self): return self.status forms.py class ModuleForm(forms.ModelForm): moduleName = forms.CharField(label='Module Name', max_length=50) ModuleDesc = forms.CharField(max_length = 256) ModuleSort = forms.IntegerField() isActive = forms.BooleanField() ModuleType = forms.IntegerField() class Meta: model = ModuleNames fields = ('moduleName','ModuleDesc','ModuleSort','isActive','ModuleType') views.py def addmodule(request,moduletype): template_name = 'module.html' modules = ModuleNames.objects.all() listmodules = ModuleTypes.objects.get(ModuleType=moduletype) modules = ModuleNames.objects.filter(ModuleType_id=listmodules) if request.method == 'GET': args = {'modules': … -
No such table upon initial Django migration
Back story: I'm creating a quiz app. I started by wanting to use Django (v=2.1.4) with Mongo via the djongo package. Everything worked until it didn't so I decided to just drop djongo and mongo entirely and go back to sqlite. I only mention it in case it is related, but I don't think it is. I made a copy of the project then deleted the original. I then created a new project with the same name and all the same apps. This created a bunch of new folders with blank files. I moved the copies of the original over to these folders (except the migration files) and replaced the blank files with the same name. I changed the mysite/settings.py file back to default to read: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'hoquidb'), } } To my knowledge this creates a fresh project ready for it's initial migration and it will use sqlite3. The problem: So I tried to do the initial migration and got a cryptic error message: (base) C:[redacted]\testabode\Hoqui\hoqui>python manage.py migrate Traceback (most recent call last): File "C:[redacted]\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "C:[redacted]\lib\site-packages\django\db\backends\sqlite3\base.py", line 296, in execute return Database.Cursor.execute(self, query, params) … -
UpdateView not populating form with existing data
So I have my UpdateView set up to send a request object to the form so I can modify a queryset in the form (based on request.user) my views.py: class DataSourceUpdateView(UpdateView): model = DataSource form_class = DataSourceForm template_name = 'engine/datasource_update.html' def get(self, request, *args, **kwargs): obj = DataSource.objects.get(pk=kwargs['pk']) self.object = None form = DataSourceForm(request) return self.render_to_response( self.get_context_data(form=form, object=obj)) def post(self, request, *args, **kwargs): form = DataSourceForm(request, request.POST, request.FILES) if form.is_valid: return self.form_valid(form) else: return self.form_invalid(form) my forms.py: class DataSourceForm(forms.ModelForm): def __init__(self, request, *args, **kwargs): self.request = request super(DataSourceForm, self).__init__(*args, **kwargs) self.fields['dataset_request'].queryset = DatasetRequest.objects.filter( creator=self.request.user) class Meta: model = DataSource exclude = ('creator', 'vote_score', 'num_vote_up', 'num_vote_down', 'file_size', 'slug') My problem is, in the template, the form is not populated with existing values. How can I fix this? -
How to start django project downloaded from bitbucket??? Error installing requirements.txt
I am new to the Wagtail cms and am taking over a friend's project.I have downloaded his repo and am trying to get it to run locally. In the site's requirements.txt file, there are some dependencies that just are not installing and giving errors: I tried it with python 2 and 3. I tried deleting modules versions. I have an answer: django-oauth-toolkit 1.2.0 has requirement django>=2.0, but you'll have django 1.11.18 which is incompatible. Can someone please give me instructions what are the steps for starting django project with wagtail when downloaded from repo. -
Save resulting JSON into SQLite - Django
I have this code: def getExchangeRates(): """ Here we have the function that will retrieve the latest rates from fixer.io """ rates = [] response = urlopen('http://data.fixer.io/api/latest?access_key=c2f5070ad78b0748111281f6475c0bdd') data = response.read() rdata = json.loads(data.decode(), parse_float=float) rates_from_rdata = rdata.get('rates', {}) for rate_symbol in ['USD', 'GBP', 'HKD', 'AUD', 'JPY', 'SEK', 'NOK']: try: rates.append(rates_from_rdata[rate_symbol]) except KeyError: logging.warning('rate for {} not found in rdata'.format(rate_symbol)) pass return rates @require_http_methods(['GET', 'POST']) def index(request): rates = getExchangeRates() return render(request, 'index.html') The resulting json from data.fixer.io has a format, like, currency | rate_of_the_currency. Something like this: "rates": {"SAR": 4.394498, "INR": 49.836962, and so on..., so, I have created this model on Django: class Fixerio_rates(models.Model): currency = models.CharField(max_length=128) rate = models.FloatField() Now, how can I save the result from my code into this model? migrations have been made already, it shouldn't be something complex to do, but since this is a migration from Flask into Django it confuses me a bit. It's kind of a different approach, Django has it's own way to deal with these things. Any ideas? -
How to structure a django model for user input when not all fields are required in all cases
I'm expanding an existing django application with new functionality. The problem is essentially as follows. Sorry if the equivalent of this question has already been asked, I'm not sure what to search for to find the solution. I have a 'store' model that contains a ManyToMany relationship to a 'departments' model, not all stores have all the same departments. I need to track daily department volumes for each store, and I need a user form to enter all this information. I don't know if I should create one model with all possible departments, or if I should create one model with one department and weight, and then create as many objects as departments for each day. Scale ability in this application will be very important going forward, and I'd like to start right. Code Below. Store departments class Department(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255, unique = True) short_name = models.CharField(max_length=32) description = models.CharField(max_length=255) def __str__(self): return self.name; Volume Data Options (Model In Question) Option 1, one model with everything: class VolumeData(models.Model): id = models.AutoField(primary_key=True) store = models.ForeignKey(stores.models.Store, on_delete=models.DO_NOTHING) date = models.DateField(auto_now_add=True,null=False,blank=False) produce = models.DecimalField(decimal_places=2,Null=True) dairy = models.DecimalField(decimal_places=2,Null=True) deli = models.DecimalField(decimal_places=2,Null=True) meat = models.DecimalField(decimal_places=2,Null=True) seafood = models.DecimalField(decimal_places=2,Null=True) coffee = models.DecimalField(decimal_places=2,Null=True) … -
Django DRF change serializer data with CreateListModelMixin
I have this class view, but I am unable to modify the serializer data to insert more data (which is needed and needs to be populated automatically). Because I am creating many instances at once, the serializer is based on kwargs['many'] = True. Any idea on how I can add another field to each serializer data? Thanks, : class ReservedServiceView(CreateListModelMixin, ModelViewSet): queryset = ReservedService.objects.all() serializer_class = ReservedServiceSerializer authentication_classes = (authentication.TokenAuthentication,) def perform_create(self, serializer): # Create an event that is a Reflection of the Reserved Service serializer_data = self.request.data for reserved_service in serializer_data: print("--------",reserved_service, flush=True) service_id = reserved_service['original_service'] original_service = Service.objects.get(pk=service_id) calendar_event = CalendarEvent() calendar_event.name = original_service.name calendar_event.description = original_service.description calendar_event.date = reserved_service['date'] calendar_event.type_id = 1 calendar_event.start_time = reserved_service['start_time'] calendar_event.end_time = reserved_service['end_time'] calendar_event.location_id = original_service.location.id calendar_event.save() reserved_service['associated_event'] = calendar_event.id print("**********1", serializer_data) print("**********2", self.request.data) serializer.save() Based in: class CreateListModelMixin(object): def get_serializer(self, *args, **kwargs): """ if an array is passed, set serializer to many """ if isinstance(kwargs.get('data', {}), list): kwargs['many'] = True return super(CreateListModelMixin, self).get_serializer(*args, **kwargs) -
Change POST method from Flask to Django
I have this code from a Flask application: def getExchangeRates(): """ Here we have the function that will retrieve the latest rates from fixer.io """ rates = [] response = urlopen('http://data.fixer.io/api/latest?access_key=c2f5070ad78b0748111281f6475c0bdd') data = response.read() rdata = json.loads(data.decode(), parse_float=float) rates_from_rdata = rdata.get('rates', {}) for rate_symbol in ['USD', 'GBP', 'HKD', 'AUD', 'JPY', 'SEK', 'NOK']: try: rates.append(rates_from_rdata[rate_symbol]) except KeyError: logging.warning('rate for {} not found in rdata'.format(rate_symbol)) pass return rates @app.route("/" , methods=['GET', 'POST']) def index(): rates = getExchangeRates() return render_template('index.html',**locals()) For example, the @app.route decorator is substituted by the urls.py file, in which you specify the routes, but now, how can I adapt the methods=['GET', 'POST'] line to a Django way? I'm a little bit confused on that, any ideas? -
Django - Form not updating in Django admin
I’m creating a profile page in my web application & I have a form to when the user makes a form submission I need the data from the form to update in django admin from the current logged in user. My Problem: The data populates in the django admin after a form submisstion however I need the data updating only and not to keep repeating listings per form submission. How do I execute this correctly with my current code? The Custom User Model I’m using is located in from users.models import CustomUser if that helps. Any help i gladly appreciated, Cheers Screenshot user_profile/admin.py from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from user_profile.forms import HomeForm from users.forms import CustomUserCreationForm, CustomUserChangeForm from user_profile.models import Listing from users.models import CustomUser # Register models here. class UserProfileAdmin(admin.ModelAdmin): list_display = ['name', 'address', 'zip_code', 'mobile_number', 'created', 'updated', 'user'] list_filter = ['name', 'zip_code', 'created', 'updated', 'user'] admin.site.register(Listing, UserProfileAdmin) user_profile/models from django.contrib import auth from django.db import models from django.urls import reverse from django.contrib.auth.models import AbstractUser, UserManager from django.contrib.auth.models import BaseUserManager from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from django.conf import settings from users.forms import CustomUserCreationForm, CustomUserChangeForm from … -
mongoengine isn't an available database backend for Django
I am trying to use mongoengine as my database I can't address the problem I downloaded mongoengine but it seems like django isn't accepting it. I get this error when I runserver django.core.exceptions.ImproperlyConfigured: 'django_mongodb_engine' isn't an available database backend. Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' I have seen some people upgrading or downgrading their version of django and it get solved like that I am using the latest version of django This as the DATABASE in the setting.py file DATABASES = { 'default': { 'ENGINE': 'django_mongodb_engine', 'NAME': 'mydatabase', } }