Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django @transaction.atomic() to prevent creating objects in concurrency
I have a ticket model, and its ticket serialiazer. The ticket model has a bought and a booked_at field. And also a unique_together attribute for show and seat. class Ticket(models.Model): show = models.ForeignKey(Show, on_delete=models.CASCADE) seat = models.ForeignKey(Seat, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) booked_at = models.DateTimeField(default=timezone.now) bought = models.BooleanField(default=False) class Meta: unique_together = ('show', 'seat') On the ticket serializer, the serializer on validation checks whether the ticket was bought or not. If it is bought, then it will raise an error. If its not bought then Check if the ticket was booked within 5 minutes. If its booked within 5 minutes, then raise an error. Else if the booking time was more than 5 minutes, than delete the old ticket and return valid. TicketSerializer: class TicketSerializer(serializers.Serializer): seat = serializers.PrimaryKeyRelatedField(queryset=Seat.objects.all()) show = serializers.PrimaryKeyRelatedField(queryset=Show.objects.all()) user = serializers.PrimaryKeyRelatedField(queryset=User.objects.all()) bought = serializers.BooleanField(default=False) def validate(self, attrs): if attrs['seat']: try: ticket = Ticket.objects.get(show=attrs['show'], seat=seat) if not ticket.bought: if ticket.booked_at < timezone.now() - datetime.timedelta(minutes=5): # ticket booked crossed the deadline ticket.delete() return attrs else: # ticket in 5 mins range raise serializers.ValidationError("Ticket with same show and seat exists.") else: raise serializers.ValidationError("Ticket with same show and seat exists.") except Ticket.DoesNotExist: return attrs else: raise serializers.ValidationError("No seat value provided.") On … -
Delete element from a database in Django
I am trying to develop a Django app able to CRUD files. At the moment I have developed the Upload-Download functionalities but things get pretty hard for me when I want to delete items. * Views.py * def list(request): # Handle file upload if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) all_docs = Document.objects.all() repeated = False if form.is_valid(): for doc in all_docs: if Document(docfile=request.FILES['docfile']).docfile == doc.docfile: repeated = True if not repeated: newdoc = Document(docfile=request.FILES['docfile']) newdoc.save() # Redirect to the document list after POST return HttpResponseRedirect(reverse('list')) else: form = DocumentForm() # A empty, unbound form # Load documents for the list page documents = Document.objects.all() # Render list page with the documents and the form return render( request, 'list.html', {'documents': documents, 'form': form} ) * Forms.py * class DocumentForm(forms.Form): docfile = forms.FileField( label='Select a file' ) * List.html * <body> <!-- List of uploaded documents --> {% if documents %} <ul> {% for document in documents %} <li><a href="{{ document.docfile.url }}">{{ document.docfile.name }}</a></li> {% endfor %} </ul> {% else %} <p>No documents.</p> {% endif %} <!-- Upload form. Note enctype attribute! --> <form action="{% url "list" %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <p>{{ form.non_field_errors }}</p> <p>{{ form.docfile.label_tag }} {{ … -
how to use paginator in results
@method_decorator([login_required, audience_required], name='dispatch') class ArticleListView(ListView): model = Article ordering = ('date_created', ) context_object_name = 'articles' template_name = 'article_list.html' def get_queryset(self): audience = self.request.user.audience audience_interests = audience.interests.values_list('pk', flat=True) queryset = Article.objects.filter(category__in=audience_interests) return queryset I want to use paginator so that only 6 articles are visible on one page -
django-rest-framework token authentication fails on production
I'm using django-rest-framework for my authentication system, using the webservices provided by Djoser. In my local Django server, I can retrieve the user from /auth/me/ without any problem. But in production I recieve 401 (Unauthorized) error. Do I need some special setting server-side to make it work properly? Thank you. -
AttributeError: 'EventView' object has no attribute 'get'
i am working on a calendar application.i am facing following error on my web page .this is my views.py .can someone please help me in it. Thanks in advance views.py from __future__ import unicode_literals from django.shortcuts import render from events.models import Event import datetime import calendar from django.urls import reverse from django.utils.safestring import mark_safe from events.utils import EventCalendar # Register your models here. class EventView(Event): list_display = ['day', 'start_time', 'end_time', 'notes'] change_list_template = 'admin/events/change_list.html' def changelist_view(self, request, extra_context=None): after_day = request.GET.get('day__gte', None) extra_context = extra_context or {} if not after_day: d = datetime.date.today() else: try: split_after_day = after_day.split('-') d = datetime.date(year=int(split_after_day[0]), month=int(split_after_day[1]), day=1) except: d = datetime.date.today() previous_month = datetime.date(year=d.year, month=d.month, day=1) # find first day of current month previous_month = previous_month - datetime.timedelta(days=1) # backs up a single day previous_month = datetime.date(year=previous_month.year, month=previous_month.month, day=1) # find first day of previous month last_day = calendar.monthrange(d.year, d.month) next_month = datetime.date(year=d.year, month=d.month, day=last_day[1]) # find last day of current month next_month = next_month + datetime.timedelta(days=1) # forward a single day next_month = datetime.date(year=next_month.year, month=next_month.month, day=1) # find first day of next month extra_context['previous_month'] = reverse('admin:events_event_changelist') + '?day__gte=' + str( previous_month) extra_context['next_month'] = reverse('admin:events_event_changelist') + '?day__gte=' + str(next_month) cal = EventCalendar() html_calendar = … -
Narrowing down a QuerySet in Django by using difference() and/or exclude()
I'm trying to narrow down a QuerySet in Django. I'm trying to do this by excluding (or taking the difference of) another QuerySet. I've already tried using difference() and exclude() but both of them do not work for some reason. Besides, I’m confused by the error messages I get. PS: I’ve looked up other answers on Stackoverflow but they haven’t solved the problem either. Here’s the code ipdb> all_products <QuerySet [<Product: P1>, <Product: P2>, <Product: P3>, <Product: P4>, <Product: P5>, <Product: P6>] ipdb> added_products <QuerySet [<Product: P1>, <Product: P2>, <Product: P3>] ipdb> all_products.exclude(added_products) *** ValueError: too many values to unpack (expected 2) ipdb> all_products.difference(added_products) *** django.db.utils.DatabaseError: ORDER BY not allowed in subqueries of compound statements. -
Multiple Search Fails With Django Haystack
I'm using django-haystack to handle the 'search' function in my app. Every thing works fine, except for the fact that multiple search is failing. I found out that haystack won't return any result if I don't input a keyword in the default search form field which is the 'q'. q = forms.CharField(required=False, label=_('Search'), widget=forms.TextInput(attrs={'type': 'search'})) But if I should input a keyword in the q field and my added fields, haystack will run through and do the search. Why is haystack not carrying out the search without keyword in the 'q' field? Forms.py class AdvancedSearchForm(SearchForm): user_type = forms.CharField(required=False) sex = forms.CharField(required=False) age = forms.CharField(required=False) user_height = forms.CharField(required=False) city = forms.CharField(required=False) country = forms.CharField(required=False) play_role = forms.CharField(required=False) play_position = forms.CharField(required=False) def search(self): sqs = super(AdvancedSearchForm, self).search() if not self.is_valid(): return self.no_query_found() if self.cleaned_data['user_type']: sqs = sqs.filter(user_type=self.cleaned_data['user_type']) if self.cleaned_data['sex']: sqs = sqs.filter(sex=self.cleaned_data['sex']) if self.cleaned_data['age']: sqs = sqs.filter(age=self.cleaned_data['age']) if self.cleaned_data['user_height']: sqs = sqs.filter(user_height=self.cleaned_data['user_height']) if self.cleaned_data['city']: sqs = sqs.filter(city=self.cleaned_data['city']) if self.cleaned_data['country']: sqs = sqs.filter(country=self.cleaned_data['country']) if self.cleaned_data['play_role']: sqs = sqs.filter(play_role=self.cleaned_data['play_role']) if self.cleaned_data['play_position']: sqs = sqs.filter(play_position=self.cleaned_data['play_position']) return sqs Settings.py HAYSTACK_DEFAULT_OPERATOR = 'OR' Backend is Whoosh. What am I missing? -
Django integrity error and not loading onetoone table on sign up form
Hello everyone thanks for your help. I have made a sign up form with django. As of now when i fill in all of the fields in the form it allows me to submit, the new user is created, then i get the error below UNIQUE constraint failed: slug_trade_app_userprofile.user_id Also in my models (below) i have a onetoone relations with the UserProfile model and for some reason none of that data is stored to the database, it only gets the username/pass/first/last. It appears to me that for some reason it submits the form the trys to submit again causing the UNIQUE issue. Not sure what i did wrong here, thanks for your help. Blow is my code views.py def signup(request): signed_in = False if request.method == "POST": user_form = UserForm(data=request.POST) profile_form = UserProfileForm(request.POST) print(user_form.is_valid()) print(profile_form.is_valid()) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() profile = profile_form.save(commit=False) profile.user = user if 'profile_picture' in request.FILES: profile.profile_picture = request.FILES['profile_picture'] profile.save() signed_in = True else: print(user_form.errors, profile_form.errors) else: user_form = UserForm() profile_form = UserProfileForm() return render(request, 'my_app/signup.html', {'user_form':user_form, 'profile_form':profile_form, 'signed_in':signed_in}) models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_picture = models.ImageField(upload_to='static/profile_pictures', blank=True ) bio = models.TextField(max_length=500, blank=True) on_off_campus = models.CharField(max_length=3, default="on", choices=CAMPUS_STATUS) forms.py class … -
When data found recieve 'str' object is not callable error
I have a very strange error when using Django Rest Framework. When ever I use the RetrieveAPIView and the data is found I get a error, when data is not found I get the normal window showing the JSON of { "detail": "Not found." } urls.py from django.conf.urls import url, include from django.contrib import admin from items.views import ItemRetrieveView urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api/(?P<pk>\d+)/$', ItemRetrieveView.as_view()), ] seriliazers.py from rest_framework import serializers from .models import Item class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = ('pk','name','desc','created') view.py- When I change RetrieveAPIViews to RetrieveUpdateDestroyAPIView I always get 'str' object is not callable even when data does not exist. from django.shortcuts import render from rest_framework import generics from .models import Item from .serializers import ItemSerializer class ItemRetrieveView(generics.RetrieveAPIView): lookup_field = 'pk' queryset = Item.objects.all() serializer_class = 'ItemSerializer' model.py from django.db import models class Item(models.Model): name = models.CharField(max_length = 30) created = models.DateField(auto_now_add = True) desc = models.CharField(max_length = 30) def __str__(self): return '%s' % (self.name) -
How can I host multipal django apps on the same webserver and give each app separate permissions to my postgres database
How can I host multipal django apps on the same webserver and give each app separate permissions to my postgres database? I can't figure out a way to do this other than by running multiple instances of apache and having each instance run as a different user that has different permissions to my database. This is very messy and hard to maintain. I would like to give the apps only the permissions they need. Any ideas would be great! Thank you. -
Download file from internet and serve to website using Django without exposing URL
I am downloading an audio file using some URL get request. I cannot expose the URL, as it contains an API-key. What is the right way to serve this file to a website? -
How use count() in a many to many field
My django project it's about money management, so one of it's type of money transaction is MultipleTransaction, it only says that it was made by multiple users together. I want to show in my interface the total value from one MultipleTransaction, using the Django template engine, how do I do that? I tried the following: template.html {% with total=transaction.value*transaction.users.count %} R${{ total }} {% endwith %} But I get this error message: TemplateSyntaxError at /historico/ Could not parse the remainder: '*transaction.users.count' from 'transaction.value*transaction.users.count' Model.py # An abstract class containing info about a Transaction made by multiple users class MultipleTransaction (Info): # All users that paid the the monthly bill users = models.ManyToManyField(User) #A file as receipt, it can be an image or a pdf. This is optional receipt = models.FileField( 'Comprovante(s)', upload_to='comprovantes', blank=True, null=True ) class Meta: # Make this class an Abstract class abstract = True # Human friendly singular and plural name verbose_name = 'Transação em Grupo' verbose_name_plural = 'Transações em Grupo' View.py @login_required def historico(request): # Those 3 lines are queries of all transactions deposits = chain(Deposit.objects.all(), MonthlyDeposit.objects.all()) withdraws = chain(Withdraw.objects.all(), EventSubscription.objects.all()) transferences = Transference.objects.all() # Then all transactions are sorted by their atribute "created_at" transactions = … -
Reusing Django Celery app in new project, fails to find other project modules or celery_app
I have a working app that uses celery to perform background file transfers and other data gathering tasks (glint) and I want to use part of this app in my new project. I've tried almost every permutation of configuration I can think of but the issue persists. To start here is the error dump from running: service celery start Traceback (most recent call last): File "/usr/lib64/python3.6/runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "/usr/lib64/python3.6/runpy.py", line 85, in _run_code exec(code, run_globals) File "/usr/lib/python3.6/site-packages/celery/__main__.py", line 54, in <module> main() File "/usr/lib/python3.6/site-packages/celery/__main__.py", line 30, in main main() File "/usr/lib/python3.6/site-packages/celery/bin/celery.py", line 81, in main cmd.execute_from_commandline(argv) File "/usr/lib/python3.6/site-packages/celery/bin/celery.py", line 793, in execute_from_commandline super(CeleryCommand, self).execute_from_commandline(argv))) File "/usr/lib/python3.6/site-packages/celery/bin/base.py", line 309, in execute_from_commandline argv = self.setup_app_from_commandline(argv) File "/usr/lib/python3.6/site-packages/celery/bin/base.py", line 469, in setup_app_from_commandline self.app = self.find_app(app) File "/usr/lib/python3.6/site-packages/celery/bin/base.py", line 489, in find_app return find_app(app, symbol_by_name=self.symbol_by_name) File "/usr/lib/python3.6/site-packages/celery/app/utils.py", line 235, in find_app sym = symbol_by_name(app, imp=imp) File "/usr/lib/python3.6/site-packages/celery/bin/base.py", line 492, in symbol_by_name return symbol_by_name(name, imp=imp) File "/usr/lib/python3.6/site-packages/kombu/utils/__init__.py", line 96, in symbol_by_name module = imp(module_name, package=package, **kwargs) File "/usr/lib/python3.6/site-packages/celery/utils/imports.py", line 101, in import_from_cwd return imp(module, package=package) File "/usr/lib64/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File … -
Access to the model element after filtering in the template
I can not access the model field after applying the filter in the template, like this: {{service_item_v|get_first|first|get_item:'price'.service}} The problem is that it throws an error: TemplateSyntaxError at /payment/ Could not parse the remainder: '.service' from 'service_item_v|get_first|first|get_item:'price'.service' The element finds correctly if you remove the field name from the dot. Also the element has this field, since it gets it if you do not apply the filter. The question is how to access the field in this case? -
Django rest Bad Request
I have extended user model to store user profile related information: class Profile(models.Model): user = models.OneToOneField(User, blank=True, on_delete=models.CASCADE, ) name = models.CharField(max_length=50, blank=True, null = True, ) age = models.IntegerField(blank=True, null = True, ) EDUCATION_CHOICES = ( ('VOC', 'Vocational'), ('DPL', 'Diploma'), ('BCL', 'Bachelor'), ('MST', 'Master'), ('DOC', 'Doctor'), ) education = models.CharField(blank=True, null = True, choices=EDUCATION_CHOICES, max_length=3, ) short_story = models.TextField(blank=True, null = True, max_length=500) ROLE_CHOICES = ( ('INT', 'Intern'), ('WOR', 'Worker'), ('SUP', 'Supervisor'), ('MAN', 'Manager'), ) role = models.CharField(blank=True, null = True, choices=ROLE_CHOICES, max_length=3, ) hobbies = models.TextField(blank=True, null = True, max_length=500) rational_thinker = models.NullBooleanField(blank=True, null = True, default=False) welcome_new_changes = models.NullBooleanField(blank=True, null = True, default=False) embrace_science = models.NullBooleanField(blank=True, null = True, default=False) if_social = models.NullBooleanField(blank=True, null = True, default=False) seek_latest_info = models.NullBooleanField(blank=True, null = True, default=False) exciting_about_job = models.TextField(blank=True, null = True, max_length=500) not_exciting_about_job = models.TextField(blank=True, null = True, max_length=500) aspiration = models.TextField(blank=True, null = True, max_length=500) @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() Its serializer: class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = '__all__' And view: @api_view(['GET', 'PUT', 'DELETE']) def profile(request): """ Get, udpate, or delete a specific profile """ try: profile = Profile.objects.get(user=request.user.id) print(profile) print(request.data) except … -
Preserve data across LiveServerTestCase test methods?
Because LiveServerTestCase inherits from TransactionTestCase, the default behavior is to delete the test data at the end of every test method. I would like to use the LiveServerTestCase class, but preserve the test data from method to method. In this example, test2 fails because the database is truncated at the end of test1. My understanding is that if I were using TestCase, it would roll back the transactions at the end of each test and return the database to its starting condition. Is it possible for me to imitate that behavior while using the LiveServerTestCase? class TestTheTests(LiveServerTestCase): @classmethod def setUpTestData(cls): print('running setUpTestData') call_command('loaddata', 'datasources.yaml' ) @classmethod def setUpClass(cls): print('starting setUpClass') cls.setUpTestData() # load the data for the entire test class super().setUpClass() @classmethod def tearDownClass(cls): print('finished tearDownClass') super().tearDownClass() def setUp(self): self.browser = webdriver.Chrome() def tearDown(self): self.browser.quit() When I run both the tests together, this test passes: def test1(self): print('test 1 running') self.assertEquals(8, DataSource.objects.count(),'There should be 8 DataSource objects in test1') This test fails: def test2(self): print('test 2 running') self.assertEquals(8, DataSource.objects.count(),'There should be 8 DataSource objects in test2') Both would pass if the database records were not being dropped at the end of test1. -
Django. How parse xml file during upload
my Views class TestFilesView(FormView): form_class = TestFilesForm template_name = 'testy/xml_files_upload.html' def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) files = request.FILES.getlist('file_field') if form.is_valid(): for f in files: instance = TestFiles( id_test=TestHeader(self.kwargs['id']), name='xx', file_name=f.name, file_field=f ) instance.save() return self.form_valid(form) else: return self.form_invalid(form) def get_success_url(self): return reverse('tests_list') How i can open uploading xml file, get "name" atribute from xml file and forward it to my istance name variable ? Can you help me ? -
Maintaining document Heading hierarchy python-docx
I am developing algorithms for extracting sections of a Docx file while maintaining document structure I managed to get headings but How do I go about getting the data between headers and maintain header hierarchy: This is what I have done so far... from docx import Document document=Document('headerEX.docx') paragraphs=document.paragraphs def iter_headings(paragraphs): for paragraph in paragraphs: if paragraph.style.name.startswith('Heading'): yield paragraph for heading in iter_headings(document.paragraphs): print (heading.text) -
Android send POST parameters
I have a Django endpoint: urlpatterns = [ path('store', views.store, name='store'), ] And this view: def store(request): x = request.POST['x'] y = request.POST['y'] z = request.POST['z'] timestamp = request.POST['timestamp'] Data(x=x, y=y, z=z, timestamp=timestamp).store() return HttpResponse(status=200) I need to make an http request to that endpoint from an android phone. I have this code right now, how I can add POST parameters? String endpoint = "http://192.168.1.33:8000/rest/store"; try { new uploadData().execute(new URL(endpoint)); } catch (MalformedURLException e) { e.printStackTrace(); } private class uploadData extends AsyncTask<URL, Integer, String> { String result; protected String doInBackground(URL... urls) { try { HttpURLConnection urlConnection = (HttpURLConnection) urls[0].openConnection(); result = urlConnection.getResponseMessage(); urlConnection.disconnect(); } catch (IOException e) { result = "404"; } return result; } protected void onPostExecute(String result) { if (result.equalsIgnoreCase("OK")) { ((TextView) findViewById(R.id.http)).setText("Database Online"); ((TextView) findViewById(R.id.http)).setTextColor(Color.GREEN); } else if (result.equalsIgnoreCase("FORBIDDEN")) { ((TextView) findViewById(R.id.http)).setText("No user for device"); ((TextView) findViewById(R.id.http)).setTextColor(Color.RED); } else{ ((TextView) findViewById(R.id.http)).setText("Can't reach server"); ((TextView) findViewById(R.id.http)).setTextColor(Color.RED); } } } How I can add x,y,z and timestamp as a POST parameters? -
Don't understand Django REST Framework KeyError
I'm working through the Django REST Framework v.2 tutorial and am getting an error I don't understand. The tutorial covers creating a simple pastebin code highlighting Web API. You start by creating the following models and loading it with a few snippets: # models.py class Snippet(models.Model): created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100, blank=True, default='') code = models.TextField() linenos = models.BooleanField(default=False) language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100) style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100) class Meta: ordering = ('created',) # Python console snippet = Snippet(code='foo = "bar"\n') snippet.save() snippet = Snippet(code='print "hello, world"\n') snippet.save() You then create a serializer class that serializes and de-serializes snippet instances into JSON: # serializers.py class SnippetSerializer(serializers.Serializer): pk = serializers.Field() # Note: `Field` is an untyped read-only field. title = serializers.CharField(required=False, max_length=100) code = serializers.CharField(widget=widgets.Textarea, max_length=100000) linenos = serializers.BooleanField(required=False) language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default='python') style = serializers.ChoiceField(choices=STYLE_CHOICES, default='friendly') def restore_object(self, attrs, instance=None): """ Create or update a new snippet instance, given a dictionary of deserialized field values. Note that if we don't define this method, then deserializing data will simply return a dictionary of items. """ if instance: # Update existing instance instance.title = attrs.get('title', instance.title) instance.code = attrs.get('code', instance.code) instance.linenos = attrs.get('linenos', instance.linenos) instance.language = attrs.get('language', instance.language) instance.style = … -
Display articles from database in bootstrap columns
I have a large database of articles, I want to display them all in bootstrap rows(3 articles per row): <div class="container"> <h1 class="mt-4 mb-4 text-center display-4">All News </h1> <div class="row"> {% for article in articles %} <div class="col-md"> <div class="card"> <h2 class="pt-2"><a href="#">{{ article.title }}</a></h2> <p class="lead"> {{ article.description }}</p> </div> </div> {% endfor %} </div> </div> The problem is that row is created outside the for statement, so every article is squeezed into one row (when there should be 3 articles per row). Is there a way to loop through the for statement, and put 3 articles in one row, close that row and then begin a new one? -
How to write a factory for this model in django using factory_boy?
I have a model in my app that contains many_to_many fields on the same model but with a filter. To be more clear this is what I have: class Places(models.Model): user = models.OneToOneField('User') common_kwargs = dict(to='places.Place', blank=True) place1_kwargs = dict( common_kwargs.items() + { 'limit_choices_to': {'site__token': 'site1'}, 'related_name': '%(app_label)s_%(class)s_place1', 'verbose_name': _('Place 1') }.items() ) place1= models.ManyToManyField(**place1_kwargs ) place2_kwargs = dict( common_kwargs.items() + { 'limit_choices_to': {'site__token': 'site2'}, 'related_name': '%(app_label)s_%(class)s_place2', 'verbose_name': _('Place 2') }.items() ) place2 = models.ManyToManyField(**place2_kwargs) and this is Place model in places app : class Place(models.Model): site= models.ForeignKey(Site, verbose_name=_('Site')) name = models.CharField(verbose_name=_('Name'),unique=True, max_length=255, db_index=True) city = models.CharField(max_length=255, verbose_name=_('City'), null=True) And this is Site model : class Site(models.Model): token = models.CharField(_('Token'), max_length=255, unique=True, editable=False) name = models.CharField(_('Name'), max_length=255) I tried to create a Factory for Places model but I didnt know how to set the filter of Site? Could Somebody help me on this ?? Thanks in advance. -
Django: linking users to models in an App (new to django><)
I am quite new to django, I know little terms... so it will be appreciated if you would answer more specifically how to implement. <3 I am working on a web development assignment about an image sharing platform. functionality involves users upload, download, delete and search images, etc. recently I have implemented 'allauth' plugin to my site so that users can login in to the site, also I created an app called 'AllImages' with a model - 'Image'. MY QUESTION IS: How can I link the users to 'AllImages' and 'Image', so that the system knows who uploaded a particular image. because I want to only let the uploader himself being able to delete his image I really know nothing about the plugin, its just done by someone haha.... this is the allauth plugin -
Validation for datefield so it doesn't take future dates in django?
I'm creating a website for my project and i have a field called Purchase_Date: class Member_Registration(models.Model): Purchase_Date=models.DateField(max_length=10, help_text="Enter the date of purchase") I want to throw an error if the user selects a date that is in the future. How do i go about this? -
How to detect the exact browser django
I have tried using request.META['HTTP_USER_AGENT'] for detecting the browser . But this returns the type of browsers list when i tested on chrome: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36 instead of just returning chrome and similarly on : edge: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/16.16299 mozilla: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0 ** I am not able to get the pattern in which it is returning values. Can anyone tell the way by which i could get the browser name