Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to implement PUT method in Django
How can I enable the user to generate only one instance of an object “bet” with a POST method and modify it through a PUT method (for example) forms.py class BetForm(forms.ModelForm): team1_score = forms.IntegerField(min_value=0, max_value=15) team2_score = forms.IntegerField(min_value=0, max_value=15) match = forms.ModelChoiceField(queryset=Match.objects.only('id')) class Meta: model = Bet fields = ('team1_score', 'team2_score', 'match') models.py class Bet(models.Model): match = models.ForeignKey(Match, on_delete=models.CASCADE, related_name='+') team1_score = models.PositiveIntegerField(default=0) team2_score = models.PositiveIntegerField(default=0) def __str__(self): return (str(self.match)) views.py def post(self, request): form = BetForm(request.POST) if form.is_valid(): form.save() team1_score = form.cleaned_data.get('team1_score') team2_score = form.cleaned_data.get('team2_score') match = form.cleaned_data.get('match') form = BetForm() return redirect ('home') args = {'form': form, 'team1_score': team1_score, 'team2_score': team2_score, 'match': match} return render(request, self.template_name, args) -
Using Flask Template in CSS <Style> tag
I a currently working on a school project that requires no usage of javascript. I need to build a list of filters where the filter lists are retrieved from sql. My css codes are placed in the style tags Here's how the original code looked like: #class1.tablefilter:checked ~ table tbody tr.class1 { display:table-row; } Here's how I should edit my code to: #{{distinct[0]}}.tablefilter:checked ~ table tbody tr.{{distinct[0]}} { display:table-row; } However, this is having an error and i believed it is due to {{distinct[0]}}. Is there any way to translate this code or any way to escape from style? -
How to separate groups of radio choices in one page? They are in conflict
I am making a kind of a survey(evaluation). My web has multiple radio choices(fields) in one page. For example, I have 3 questions in a page, each has 5 radio choices. If I select the choice 3 in No.1 question and then the 4 in No.2 question, No.1 choice disappeared(choice 3). I guess it's conflict between No.1 and No.2. So, I can pick just one choice for all questions. ---------------------------------------------------------- I guess something wrong since I display many forms (not one form) in same page. But I don't know why. Help me... My Code is following (Never mind about Korean) html {% extends 'base.html' %} {% load staticfiles %} {% block content %} <form method="post" id='evaluate_answer_form' novalidate> {% csrf_token %} {% for q, form in questions %} # q:question object / form:answer form <p> {# Include the hidden fields #} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {# Include the visible fields #} {% for field in form.visible_fields %} <div class="fieldWrapper"> {{ field.errors }} {{ q.ask }} {{ field }} </div> {% endfor %} </p> {% endfor %} <button type="submit">Submit</button> </form> {% endblock %} forms.py class AnswerForm(forms.ModelForm): AGREEMENT_CHOICES = ( ('5', '매우 동의함'), ('4', '동의함'), … -
I can not change the date format in django drf
I have drf model which is containe DateField. That field default format is "YYYY-MM-DD" just i want to convert "DD-MM-YYYY" how can is possible. class SpaUserSerializer(serializers.ModelSerializer): date_joined = serializers.ReadOnlyField() birthdate = serializers.DateField(format="d-m-Y", input_formats=['d-m-Y',]) -
django, unable to create new model, throw DatabaseError 1050, "Table 'XXX' already exists"
I am under production environment so the python3 manage.py migrate APP -fake does not work for me. My company has dev, qa, pre,pre2 and prd environment. I simply added a new model class MyModel(models.Model): column1 = models.ForeignKey(SomeAPP) column2 = models.ForeignKey(SomeApp2) column3 = CharField(max_length=50) It works fine under all other environments except prd. I tried to delete the table in MySQL and re-build, failed. I did search django_mirgrations table and did not find any record related my brand new app. What are the possible reasons caused this and how can I fix it? django 1.11.4 and mysql 5.7. And, I tried to delete the latest migration files under prd environment, successfully built (but when I fetch mysql, the table comes). However, when I tried to alter column, the migration file under other environments is migrations.AlterField yet in prd migration file it is migrations.CreateModel(since I manually ran a DROP TABLE XXX?) -
Get modelform to output custom name for modelform fields
I have a modelform: class SubmitDomain(ModelForm): emailVerified = forms.CharField(max_length=50, required=False, widget=forms.TextInput(attrs={'class': 'validate', 'id': 'emailVerified'})) domainNm = forms.CharField(max_length=40, required=False, widget=forms.TextInput(attrs={'class': 'validate', 'id': 'domainNm'})) In versions of django before 2+ I was able to just create verbose_name=something to change the display value of a modelform's field name different from what the model's field name actually is. For example, on my form it displays: domainNm and emailVerified How can I get it to display: Domain Name Verifying Email Thank you in advance. -
django-oscar category API view missing from django-oscar-api
I have a django-oscar project which I use django-oscar-api. I am able to work with the API well but I noticed that there is no API view for the categories and some other things like Promotions. My question now is is it possible to write API codes to get the categories and promotions and if yes how can this be done. If one would use restframework to create new serializer class etc. I have made my research and was unable to come up with something good. any help would be appreciated -
Django ORM queryset takes integer filed as string
results = UmUrl.objects \ .filter(created_at__gte=sdate, created_at__lte=edate) \ .annotate(timeValue=self.get_date_format(param)) \ .values('timeValue') \ .order_by('timeValue') \ .annotate(blocked=Sum(Case(When(operation=0, then=1), default=0, output_field=models.IntegerField()))) \ .annotate(unBlocked=Sum(Case(When(operation=1, then=1), default=0, output_field=models.IntegerField()))) 'operation' filed is Integer type. This code creates an sql query, but in the sql reult 'when' parameters is shown as string type. So that it does not work. sql output like that. How can I solve this problem? {"query": "SELECT DISTINCT CONCAT(EXTRACT('year' FROM \"um_url\".\"created_at\" AT TIME ZONE 'Europe/Istanbul'), CONCAT('-', EXTRACT('month' FROM \"um_url\".\"created_at\" AT TIME ZONE 'Europe/Istanbul'))) AS \"timeValue\", SUM(CASE WHEN \"um_url\".\"operation\" = '0' THEN '1' ELSE '0' END) AS \"blocked\", SUM(CASE WHEN \"um_url\".\"operation\" = '1' THEN '1' ELSE '0' END) AS \"unBlocked\" FROM \"um_url\" WHERE (\"um_url\".\"created_at\" <= '2018-06-02 15:47:51.857000+00:00' AND \"um_url\".\"created_at\" >= '2018-06-01 15:47:51.857000+00:00') GROUP BY CONCAT(EXTRACT('year' FROM \"um_url\".\"created_at\" AT TIME ZONE 'Europe/Istanbul'), CONCAT('-', EXTRACT('month' FROM \"um_url\".\"created_at\" AT TIME ZONE 'Europe/Istanbul'))) ORDER BY \"timeValue\" ASC", "empty_check": "true"} -
**kwargs always giving none in django
Somewhere in my views i am redirecting as : return redirect('camera_login', success='False' ) In my urls.py : url(r'^', CameraLoginView.as_view(), name = "camera_login"), url(r'^(?P<success>[a-zA-Z0-9-]+)/$', CameraLoginView.as_view(), name = "camera_login"), Now i can see the url is being redirected to localhost:8000/False in my browser, and the camera_login.html page is rendered, but when i debug the code, my **kwargs is always none. class CameraLoginView(View): def get(self, request, *args, **kwargs): print('kwargs' , self.kwargs) success = None print('args ', args) return render( request, 'camera_login.html', {'success': success}) in terminal kwargs {}, kwargs is always empty? I don't know where i am going wrong. Thanks. -
Overriding admin form for a model in django
Here's my models.py from multiselectfield import MultiSelectField class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') users = User.objects.values_list('id','username') authorized = MultiSelectField(choices=users, null=True) def __str__(self): return self.question_text My problem is that while server is running after user register my choices field are not updating till rerun my server. I did some research and i found solution for that: https://mschmitt.org/blog/dynamic-django-form-choice-labels/ http://www.ilian.io/django-forms-choicefield-with-dynamic-values/ I have no idea how to override model in forms + i need to override model in django admin forms. any pointers would be great! thanks in advance -
Nginx, https and websocket chat not working with Django
after adding the SSL certificates successfully, the certificate is blocking the python scripts that uses websockets library in our website's chat. Has anyone experienced anything similar? Thanks -
Change marker in map
I am struggling with changing the marker in my javascript code. In spite of having referred to numerous examples on the web, none of the solutions seem to work for me. I am a beginner, so please try being patient with me. ` {% for data in datadump %} var latLng = new google.maps.LatLng({{data.latitude}},{{data.longitude}}); var marker = new google.maps.Marker({ position: latLng, map: map, title: '{{data.locationid}}', label: '{{data.observationdate}}', icon: "{% static '/darkskymap/img/markers/rocket-15.svg' %}" }); {% endfor %}` I have tried different ways to supplying the image to the marker variable but none seem to work. Solution N° 1 : Static file path as input to icon parameter like the one in example above. Solution N° 2 : Relative path as input to icon parameter icon: "/darkskymap/static/darkskymap/img/markers/rocket-15.svg" Solution N° 3 : URL path as input to icon parameter var image = "https://www.pythonanywhere.com/user/......./darkskymap/static/darkskymap/img/markers/rocket-15.svg" icon: image Can anyone please help me ? -
Django - How to avoid query the same obj
I apologize for the extremely long message, but I'm new with this and need your knowledge and advice about Python and Django. Basically, I am developing a small "questions and answers" game.I have a model with all the questions with their codes, etc. Participants will login (they could be from 5 to 20 participants on each game), and on the screen, they will have an option that says "ASK A QUESTION". All participants can click the button at the same time, so how can I be sure that each user gets a different question?. Obviously I already thought, in placing true / false fields, if the question was already used, but the idea is to avoid duplication. I come from JAVA, so with synchronized methods are not going to allow the method to be accessed at the same time, avoiding duplicate results. So is there something similar in Python? or is there a way to avoid that duplication? Thanks a lot! -
haystack can't parse a query
I am working on a Django application and want to perform some queries. I use haystack with solr. I have a model B that has a foreign_key to model A. I need to get object of A that has certain id. Then I need to get all objects of B that point to it. I tried: sqs = SearchQuerySet().filter(content=something).models(A).filter(id__in=[id_of_A_object_i_need]).models(B) And I got an error: SolrError: Solr responded with an error (HTTP 400): [Reason: org.apache.solr.search.SyntaxError: Cannot parse '( AND id:("18"))': Encountered " AND "AND "" at line 1, column 2. Was expecting one of: NOT ... "+" ... "-" ... BAREOPER ... "(" ... "*" ... QUOTED ... TERM ... PREFIXTERM ... WILDTERM ... REGEXPTERM ... "[" ... "{" ... LPARAMS ... "filter(" ... NUMBER ... TERM ... ] Can you help me? -
Difficulty playing/understanding video in Django
I'm trying to play video that I as administrator will upload in a model for playing on my homepage. Maybe later I will give users the option to upload their own videos, but for now I'm just focusing on this basic capability. My problem is that I cannot get the video to render on the page. It may be that my video file is uploading to the wrong directory, or that my html is pointing to the wrong directory. However, when I access the admin and I click on the uploaded file, Django shows a video window with a play button crossed through, so it seems that the Django admin cannot access the video either. Here's my model: class Video(models.Model): name = models.CharField(max_length=100, null=True, blank=True) file = models.FileField(null=True, blank=True, upload_to='videos') def __str__(self): return self.name Here's my view: class home(generic.ListView): model = VideoModel template_name = 'hide/base.html' def get_queryset(self): v = VideoModel.objects.filter(name='Video 1') return v *It may be the problem is with the view and the query. I'm not sure if querying a video file is the same as querying a CharField or whatever. In my project directory I have a media folder and a static folder. Within the media folder I've … -
User Follower model on Django. Cannot use add() on a ManyToManyField which specifies an intermediary model. Use accounts.Contact's Manager instead
I am new to Django, Please forgive any silly mistakes in code or logic, Intro: I am trying to create a user follower model in Django. Where users can follow and unfollow other users on the sites Error: I have made the models for my follow/unfollow I have also made the views I am getting this error AttributeError at /accounts/admin/follow/ Cannot use add() on a ManyToManyField which specifies an intermediary model. Use accounts.Contact's Manager instead. The obj.followers.add(user) is highlighted in the traceback as the origin of the error Below are my models.py from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) city = models.CharField(max_length=100) country = models.CharField(max_length=100) def get_absolute_url(self): return reverse('accounts:profile', kwargs={'username': self.user.username}) class Contact(models.Model): user_from = models.ForeignKey(User, related_name='suppporter') user_to = models.ForeignKey(User, related_name='leader') def __str__(self): return '{} follows {}'.format(self.user_from, self.user_to) User.add_to_class('following', models.ManyToManyField('self', through=Contact, related_name='followers', symmetrical=False)) I think the models.py may be good. The fault I believe is in my views. Below is my view.py class FollowToggle(LoginRequiredMixin, RedirectView): def get_redirect_url(self, *args, **kwargs): username = self.kwargs.get('username') print(username + " This is the user who will be followed") # This prints correct profile = get_object_or_404(Profile, user__username=username) print(profile) # This prints correct obj = get_object_or_404(User, username=username) print(obj) # This prints correct url_ = … -
Filter on datetime field in Django in Postgres throwing error
I have a django model as follows class Batch(db.Models): start = models.DateTimeField() stop = models.DateTimeField(null=True) class Meta(Base.Meta): indexes = [ models.Index(fields=['start', 'stop']) ] I have a bunch of entries in the table that I would like to filter on the start and stop field. I am trying to perform a query like below Batch.objects.filter( start__gte = datetime.datetime(2018, 1, 1, 0, 0, 0, tzinfo=pytz.utc) ) But I encounter error below Traceback (most recent call last): File "<console>", line 1, in <module> File "/Users/r92vx/myapp/venv3/lib/python3.6/site-packages/django/db/models/query.py", line 251, in __repr__ return '<%s %r>' % (self.__class__.__name__, data) File "/Users/r92vx/myapp/venv3/lib/python3.6/site-packages/django/db/models/base.py", line 513, in __repr__ return '<%s: %s>' % (self.__class__.__name__, self) TypeError: __str__ returned non-string (type NoneType) I am not sure what I am doing wrong. As per the examples in documentation this should be working. Any help is appreciated. TIA. -
No reverse match in url
I am having no reverse match error. In my views.py : return redirect('list_posts_by_status', status) In urls.py : url(r'^list/(?P<status>\w+)/$', BlogListView.as_view(), name='list_posts_by_status'), Is there something obvious that i am missing, thanks. -
django : retrieving data from database
I have this queryset function for a filesystem browser class-based view : def get_queryset(self): try: DoneScan.objects.get(done=self.kwargs['pk']) except ObjectDoesNotExist: self.directory = Directory.objects.get(id=self.kwargs['pk']) fl = FileSystemManager(self.directory.path) fl.map_directory() fl.db_insert() finally: return Directory.objects.filter(parent_id=self.kwargs['pk']) It tries to get a directory path object from the "already scanned directories" table, if it fails it maps the directory and insert the result in the database. And finally, returns all children directories of the directory requested. Some may have understood the issue there already : the less the directory contains, the longest will be the response. I wondering then if the way to get my queryset is the best (on a programming logic point of view), any better idea ? Thanks -
ERROR:django.security.DisallowedHost on waitress server
I am using waitress for a little django application. It was working fine until recently. The very only change that was made to the application is adding Celery, which I can't find a connection with. Now every time I do localhost:8000 (on my development) or the intranet production server (10.10.10.1:8000) returns Bad Request 400. In localhost, it displays ERROR:django.security.DisallowedHost but I have added the addresses in ALLOWED_HOST[] and even tried ALLOWED_HOST=['*'] I am at loss over what to do. I saw suggestions for ngx and apache. Unless a must, i love to keep waitress cos it was working so well. -
when I type python in my terminal, should I get python2 or python3?
I am using a Mac and have Python 2 and 3 installed. However, I'm getting some inconsistence on the Internet that someone typed "python" and get the version of python3 while I have to type "python3" to get python3 and "python" or "python2" to get python2. I decided to study the Django and I read that the Django will be only supporting python3 but the commands on the official site all starting with "python ..." instead of "python3 ...". Therefore, I am confused how is everyone using python3 with the Django or how exactly does everyone use python3? -
Django doesn't load static files ValueError("Missing staticfiles manifest entry for '%s'" % clean_name)
is my first app in Django and I am trying to prepare my Django (2.0) application for production, but I am unable to make the static files load properly using WhiteNoise I keep having all the time the next error in my log ValueError("Missing staticfiles manifest entry for '%s'" % clean_name) ValueError: Missing staticfiles manifest entry for 'css/inicio.css' [02/Jun/2018 14:40:37] ERROR [django.server:124] "GET /participation/prueba HTTP/1.1" 500 27 I have the following settings.py ... DEBUG=False DJANGO_APPS = ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', #Delete for development whitenoise.runserver_nostatic 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', 'django.contrib.sites' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ... STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles/') STATICFILES_DIRS = ( (os.path.join(BASE_DIR, 'static')), ) STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' I have all my static files in a folder call static at root level, when I run manage.py collectstatic I get generate all the static files in the staticfiles dir, but somehow still I don't manage to make it run. I try to isolate the problem and I am using the following template <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> {% load static %} <link rel="stylesheet" href="{% static "css/inicio.css" %}"> </head> <body> {% for categoria in categoria_list %} <p> {{ … -
Apache error 500 due to Django form
guys! I'm making online shop and I've added form for discount coupons to my cart: <form action="{% url "cupon:apply" %}" method="post" class="light"> <div class="row"> <div class="col-sm-3"> {% csrf_token %} {{ cupon_apply_form }} <br> <input class="btn btn-primary bold" style="width: 140px;height: 30px" type="submit" value="ПРИМЕНИТЬ"> </div> ... </div> </form> Without this form everything work fine but when I add it to my html file I get Server Error (500). But in PyCharm on my computer everything works fine. This is my urls.py file for coupons: urlpatterns = [ path('apply/', views.CuponApply, name='apply'), ] And my views.py file: @require_POST def CuponApply(request): now = timezone.now() form = CuponApllyForm(request.POST) if form.is_valid(): code = form.cleaned_data['code'] try: cupon = Cupon.objects.get(code__iexact=code, valid_from__lte=now, valid_to__gte=now, active=True) request.session['cupon_id'] = cupon.id except Cupon.DoesNotExist: request.session['cupon_id'] = None return redirect('cart:CartDetail') What am I doing wrong here? Also Apache doesn't give any info in error log. Thank you. -
Error - UnboundLocalError at /home/ local variable 'team1_score' referenced before assignment
Getting this error on django This is my views.py def post(self, request): form = BetForm(request.POST) if form.is_valid(): form.save() team1_score = form.cleaned_data.get('team1_score') team2_score = form.cleaned_data.get('team2_score') match = form.cleaned_data.get('match') form = BetForm() return redirect ('index') args = {'form': form, 'team1_score': team1_score, 'team2_score': team2_score, 'match': match} return render(request, self.template_name, args) This is my forms.py class BetForm(forms.ModelForm): team1_score = forms.IntegerField(min_value=0, max_value=15) team2_score = forms.IntegerField(min_value=0, max_value=15) class Meta: model = Bet fields = ('team1_score', 'team2_score', 'match') The error is on this line: args = {'form': form, 'team1_score': team1_score, 'team2_score': -
Retreiving an object id from a queryset in Django
I have a contract table in my database, the contracts are based mainly on a listing and two users. When creating the contract I want to check if the contract already exists and if so redicrect the user(s) to the created contract. Here is the code in my view: def create_proposal (request, conversation_pk): existing_proposal = Contract.objects.filter(users__in=[user_1, user_2]).filter(listing_id=listing).values_list('id', flat=True) Then I redirect using: if existing_proposal.exists(): messages.success(request, "the proposal already exists") return HttpResponseRedirect(reverse('agreement:agreement', kwargs={'pk': existing_proposal[0].pk})) However, I am getting the following error: AttributeError at /en/agreement/create_proposal/32 'int' object has no attribute 'pk'