Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Importing in Pycharm (Django) not working Module not found
I am trying to do some tests in a Django project. Well, tests stop at some point (all pass, but suddenly stop), and the only thing I have notice is the import in my views.py might not be working. This is my project structure: And this is the console log I do not understand why the module is not found (Or "no module named"). I have tried importing it in different ways but give errors. -
API Button add Params
I am trying to create button with POST Api. After click on button there is call post api method but I want to add there also parameters to body of api. Could you help how to add params ? Thank you. Code of form and button: <form action="http://localhost:8000/api/customer/pozicanie/add/" method="post"> <button name="foo" value="Add" href="http://localhost:8000/">Add</button> </form> Code of Api: @csrf_exempt def customer_add_pozicanie(request): if request.method == "POST": pozicanie = Pozicanie.objects.create( uzivatel = request.user, name = request.POST["heslo"], stojan = randint(1,20), ) return redirect('http://localhost:8000/chcembike/'); -
OneToOneField keeps getting set to None in Django?
I have a model Family which is similar to the following: from django.db import models from django.contrib.auth.models import User class Family(models.Model): employee_user = models.OneToOneField(User, blank=True, null=True, related_name='employee_family') partner_user = models.OneToOneField(User, blank=True, null=True, related_name='partner_family') I'm trying to set an employee_user for the family. Firstly, I'm trying it in the Django admin UI. If I select the user Kurt Peek from the dropdown menu, when I click "Save" it says the family was changed successfully: Yet when I go back to the family detail page, I see that there is no 'Employee User' set: I observe similar behavior using the Django shell. In [1]: from lucy_web.models import * In [2]: family = Family.objects.get(employee_first_name='Kurt') In [3]: family.employee_user In [4]: user = User.objects.get(email='kurt@startwithlucy.com') In [5]: family.employee_user = user In [6]: family.save() In [7]: family.employee_user In [8]: user Out[8]: <User: Kurt Peek> As seen from command 7, family.employee_user is still None even after setting it to user and saving, even though user is not None. Any ideas why the employee_user field is not updating, either in the Django Admin UI or in the shell? -
DataFlow failed with return code 1 with Airflow DataflowHook.start_python_dataflow
And this is my code below. I am getting the below error, when I run the below code. I am trying to transform gvcf/vcf files in my google cloud storage to bigquery using gcp-variant-transforms api. [2018-06-06 16:46:42,589] {models.py:1428} INFO - Executing on 2018-06-06 21:46:34.252526 [2018-06-06 16:46:42,589] {base_task_runner.py:115} INFO - Running: ['bash', '-c', u'airflow run GcsToBigQuery gcsToBigquery_ID 2018-06-06T21:46:34.252526 --job_id 168 --raw -sd DAGS_FOLDER/GcsToBigQuery.py'] [2018-06-06 16:46:43,204] {base_task_runner.py:98} INFO - Subtask: [2018-06-06 16:46:43,202] {init.py:45} INFO - Using executor SequentialExecutor [2018-06-06 16:46:43,284] {base_task_runner.py:98} INFO - Subtask: [2018-06-06 16:46:43,283] {models.py:189} INFO - Filling up the DagBag from /apps/airflow/dags/GcsToBigQuery.py [2018-06-06 16:46:43,853] {base_task_runner.py:98} INFO - Subtask: [2018-06-06 16:46:43,852] {gcp_dataflow_hook.py:111} INFO - Start waiting for DataFlow process to complete. [2018-06-06 16:46:46,931] {base_task_runner.py:98} INFO - Subtask: [2018-06-06 16:46:46,930] {GcsToBigQuery.py:48} ERROR - Status : FAIL : gcsToBigquery: Not able to run: DataFlow failed with return code 1 [2018-06-06 16:46:46,931] {base_task_runner.py:98} INFO - Subtask: [2018-06-06 16:46:46,930] {python_operator.py:90} INFO - Done. Returned value was: None Please help me with this issue. Thanks! from datetime import datetime, timedelta from airflow import DAG from airflow.contrib.hooks.gcp_dataflow_hook import DataFlowHook from airflow.operators.python_operator import PythonOperator import logging default_args = { 'owner': 'My Name', 'depends_on_past': False, 'start_date': datetime(2018, 6, 6), 'email': ['MY Email'], 'email_on_failure': True, 'email_on_retry': False, 'retries': 2, … -
AnyMail not sending an email in a Django test, despite that mail.outbox is empty?
I'd like to write a Django unit test which tests that an email is sent without actually sending it (as described in https://docs.djangoproject.com/en/2.0/topics/testing/tools/#email-services), but can also be configured to send an actual email (to inspect its formatting, etc.). Right now, I have just an 'ordinary' test: from django.test import TestCase, override_settings from django.core import mail from lucy_web.test_factories import FamilyFactory, UserFactory from lucy_web.views.app_invite import send_activation_email # @override_settings(EMAIL_BACKEND="anymail.backends.mailgun.EmailBackend") class SendActivationEmailTestCase(TestCase): def test_send_activation_email(self): user = UserFactory(email='kurt@startwithlucy.com') family = FamilyFactory(employee_user=user) send_activation_email(user=user) self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].recipients(), [user.email]) self.assertIn( f"Your activation code is {family.activation_code}.", mail.outbox[0].body) (The test makes use of factory_boy test fixtures for certain models). This test passes, but if I comment in the override_settings decorator, I get an error: (venv) Kurts-MacBook-Pro-2:lucy-web kurtpeek$ python manage.py test lucy_web.tests.test_app_invite Creating test database for alias 'default'... System check identified no issues (0 silenced). F ====================================================================== FAIL: test_send_activation_email (lucy_web.tests.test_app_invite.SendActivationEmailTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/kurtpeek/Documents/Dev/lucy2/lucy-web/lucy_web/tests/test_app_invite.py", line 15, in test_send_activation_email self.assertEqual(len(mail.outbox), 1) AssertionError: 0 != 1 ---------------------------------------------------------------------- Ran 1 test in 0.787s FAILED (failures=1) Destroying test database for alias 'default'... Since the mail.outbox is empty, I would expect that I would receive an actual email, but I checked my inbox and didn't receive anything. For the sake of completeness, … -
Django 2.0 Admin: Does delete confirm even if the ForeignKey on_delete field is set to CASCADE?
Switching from Django 1.9 (I know, it's out of compliance, hence the upgrade) to 2.0. I see on_delete is a required field for all ForeignKey fields. Previously when I would delete an object from Django Admin, it would run a check and confirm if I wanted to delete records with FKs to the object I'm deleting. Regarding the new field, if I set it to cascade (the default behavior previously), will it still confirm before deleting or do I need to use PROTECT and then do the foreign key deletes myself if I choose? I liked being able to delete something and see what it was going to take out before actually deciding whether or not to keep the record or delete it and all cascaded records. Just want to know if I can use this technique to see what is attached to a record before I decide how to use the on_delete option. Thanks -
Django Social Auth namespace error
I get this error 'social' is not a registered namespace when i click on the link to login. It redirect me to this url: http://127.0.0.1:8000/mysite/oauth/login/google-oauth2/ Even tho i have like this in my index.php: <a href="{% url 'mysite:social:begin' 'google-oauth2' %}">Login with Google</a><br> And this is how it looks like in mysite/urls.py path('oauth/', include('social_django.urls', namespace='social')), Also added this line into the settings: SOCIAL_AUTH_URL_NAMESPACE = 'social' But nothing seems to fix the error. -
Django rest framework GenericAPIView permissions
I am trying to add permissions to my views in the django rest framework. I've gone ahead and followed the instructions here: http://www.django-rest-framework.org/api-guide/permissions/#setting-the-permission-policy to set things globally and everything seems to be working. Except, I don't want to restrict my entire API, just certain parts of it. Further down, they have the code for adding permissions in your classes for specific views using permissions_classes like so: from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.views import APIView class ExampleView(APIView): permission_classes = (IsAuthenticated,) def get(self, request, format=None): content = { 'status': 'request was permitted' } return Response(content) I have a slightly different view than this and I am using the generics.GenericAPIView and hitting a snag when trying to set permissions in this way: from games.models import Game from games.serializers import GameSerializer from rest_framework import mixins from rest_framework import generics from rest_framework.permissions import IsAuthenticated class GameList(mixins.ListModelMixin, generics.GenericAPIView): permission_classes = (IsAuthenticated,) queryset = Game.objects.all() serializer_class = GameSerializer def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) class GameDetail(mixins.RetrieveModelMixin, generics.GenericAPIView): queryset = Game.objects.all() serializer_class = GameSerializer def get(self, request, *args, **kwargs): return self.retrieve(request, *args, **kwargs) The API just simply stops responding when setting permissions in this way. What's going on here? Am I … -
AllAuth (Django) - Obtaining User Permission to Contact
I'd like to ask new users for their permission to contact them about updates regarding my application. I can't seem to find a way to set this up via AllAuth. Is this built in or do I need to add it? I am using AjaxSignupView (code pasted below). Is there a method I can overwrite to save the boolean value to the model? class AjaxSignUpView(SignupView): def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) if form.is_valid(): response = self.form_valid(form) return _ajax_response( self.request, response, form=form, data=self._get_ajax_data_if()) else: errors = [err for err in form.errors.values()] print(errors) return JsonResponse({'errors': errors}) -
Django orm - how to get distinct items of field within query of distinct dates
I have the following models: class Event(models.Model): date = models.DateTimeField() event_type = models.ForeignKey('EventType') class EventType(models.Model): name = models.CharField(unique=True) I am trying to get a list of all dates, and what event types are available on that date. Each item in the list would be a dictionary with two fields: date and event_types which would be a list of distinct event types available on that date. Currently I have come up with a query to get me a list of all distinct dates, but this is only half of what I want to do: query = Event.objects.all().select_related('event_type') results = query.distinct('date').order_by('date').values_list('date', flat=True) Now I can change this slightly to get me a list of all distinct date + event_type combinations: query = Event.objects.all().select_related('event_type') results = query.order_by('date').distinct('date', 'event_type').values_list('date', 'event_type__name') But this will have an entry for each event type within a given date. I need to aggregate a list within each date. Is there a way I can construct a queryset to do this? If not, how would I do this some other way to get to the same result? -
Waitress Nginx Unable to serve static files with relative path
I am using waitress as a WSGI to serve my Django application and I am using nginx as a reverse proxy. When I am giving the absolute path to the static files it works fine but if I try to give relative path it doesn't work. server { listen 8000; server_name localhost; charset utf-8; client_max_body_size 75M; access_log "logs/nginx-access.log"; error_log "logs/nginx-error.log"; location /static/ { alias "C:/Users/mateen/Documents/MDA-Configuration-Server/static/"; #alias "static/"; } location / { proxy_pass http://127.0.0.1:8008; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } The commented part in location /static/ is what I want to make it work. I have also made sure that the file location is correct. I gave the relative paths in access log and error log and they work fine. Is it something I am missing here? -
Reverse for 'x' not found. 'x' is not a valid view function or pattern name
I have three pages - homepage, http://127.0.0.1:8000/, displaying one paragraph sentence and two links in the header. and list of pizzas, http://127.0.0.1:8000/pizzas . Now i was trying to add links for each pizza on http://127.0.0.1:8000/pizzas page, so that one could click on them and see what toppings were available. I'm probably stuck because of my decision to use paths instead of url() for mapping urls, which the book i'm following uses. Error during template rendering In template C:\pizza\pizzeria_app\templates\pizzeria_app\base.html, error at line 6 base.html is the template that pizzas.html inherits from. Error : NoReverseMatch at /pizzas Reverse for 'pizza_w_toppings' not found. 'pizza_w_toppings' is not a valid view function or pattern name. pizzas.html - {% extends "pizzeria_app/base.html" %} {% block content %} <h1> Available Pizzas : </h1> <ul> {% for pizza in pizzas %} <li> <a href = {% url 'pizza_w_toppings' %}> {{pizza}}</a><li> {% empty %} <p> We're outta Pizzas. next time bro! <p> {% endfor %} </ul> {% endblock content %} app/urls.py : urlpatterns = [ #homepage path('', views.index), #show available pizzas path('pizzas', views.pizzas), path('pizzas/<int:pizza_id>', views.pizza_w_toppings, name="pizza_w_toppings") Views: I'm new to StackOverflow and can't figure out how to add my views.py. i attached a picture, sorry views.py screenshot -
How to set cookie values and then immediately redirect to the next page and display what's in them
So I need to store two variables from one view and redirect to another view and display them. The obvious solution would be to use sessions but I don't have access to sessions because I don't have a database for this project so I'm trying to do sessions client sided because this isn't really a security issue anyways. This is my attempt so far: View where I set the cookies: response = HttpResponse('/result') response.set_cookie('passes', True) response.set_cookie('errors', []) v = jsonschema.Draft4Validator(schema) #Uses lazy validation to add all errors to validationErrors array for error in v.iter_errors(jsonFile): validationErrors.append(error) response.set_cookie('passes', False) for error in validationErrors: error.schma_path = error.schema_path.__str__()[5:] print error.schma_path print error.schema_path response.set_cookie('errors',validationErrors) ... return redirect('/result') View where I try to get the cookies: passes = request.COOKIES.get('passes',"Doesn't Exist") errors = request.COOKIES.get('errors', "Doesn't Exist") return render(request, 'result.html', context = {'errors': errors, 'passes': passes}) passes and errors isn't set because they both return Doesn't Exist. How would I do this without returning to the original page? I don't want to return response where response = render_to_response(current view's template) because it defeats the purpose of what I'm trying to do. -
After overriding the Clean method in AuthenticationForm, authenticate returns None, and does not handle any errors
friend. There was a need to override the Сlean method in AuthenticationForm to further check for the presence of an attribute before the user can log in. Forms.py: from django.contrib.auth.forms import AuthenticationForm as BaseAuthenticationForm from django.contrib.auth.models import User from inc.models import Account, UserProfile, Counter class AuthenticationForm(BaseAuthenticationForm): def clean(self): username = self.cleaned_data.get('username') user = User.objects.filter(username = username).first() if user != None: print(user) if not user.is_superuser and not user.is_staff: account = Account.objects.filter(num_account = UserProfile.objects.filter(user__username = username).first().num_account).first() have_counter = Counter.objects.filter(num_account = account).all() if not have_counter: raise forms.ValidationError('Some text...') return self.cleaned_data Views.py: from django.contrib.auth import login, authenticate from .forms import AuthenticationForm def LogIn(request): if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) print(user) login(request, user) return redirect('/') else: print(form.errors) else: form = AuthenticationForm() return render(request, 'userprocessing/login.html', {'form': form}) The problem is as follows. When I try to register as a user who is in the database everything works as it should, but when I enter a non-existent login I throw out: AnonymousUser' object has no attribute '_meta' which points to login(request, user). The error is understandable, it can not login the user which does not return user = authenticate(username=username, password=password) (it returns None). The … -
from Django forms to pandas DataFrame
I am very new to Django, but facing quite a daunting task already. I need to create multiple forms like this on the webpage where user would provide input (only floating numbers allowed) and then convert these inputs to pandas DataFrame to do data analysis. I would highly appreciate if you could advise how should I go about doing this? form needed -
How to display clicked item/ image in a new view in django?
Imagine you got a feed of images and as soon as you click on one image it displays it in a new template, kind of like a comment view where the picture is on top and the comments section below. The only thing I achieved was that I displayed the clicked image in a new tab: <a href="{{image.body.url}}" target="_blank"> <img style="width:250px; background-color:yellow;flex-shrink: 0;min-width: 100%;min-height: 100%" src="{{ image.body.url }}" /> </a> It is not what I want though... :/ So I imagined it smth like this: making an anchor link that passes this clicked image url to a new view(like above: "image.body.url") in a new template take this url and display it as an image Hopefully I described it undersandably. Thx in advance :) -
Django - getting entries from a foreign key relationship for csv output
I am exporting some data in a Django view to csv, simplified code example below. I want to get all the games from the Game model and for each game, get the scores (one to many relationship). I am getting the error tuple object has no attribute score_set so the below code which I have tried doesn't appear to be the correct way to do this. I have no problem with getting the Game objects exported alone. Can anyone point me in the right direction please? response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="stuff.csv"' writer = csv.writer(response) writer.writerow(['Name', 'Details', 'More details']) games = Game.objects.filter(user=request.user).values_list('name', 'details', 'more_details') for game in games: scores = game.score_set.all().values_list('score', 'date_played') writer.writerow(game) writer.writerow(scores) return response -
Django logging with Python's RotatingFileHandler
I'm having trouble getting the RotatingFileHandler class to create a new file once the value for maxBytes has been reached. I noticed the error first when I ran migrations on a staging server after adjusting my maxBytes down to a level that would necessitate a new file. The error is: PermissionError: [Errno 13] Permission denied /file.log -> file.log.11 I've subsequently tried to reproduce this error when I force Django to write to the debug file however nothing happens. I know this is a known issue possibly due to multiple processes setting up logging however all the SO articles on this are from 2010-2014 so I'm wondering if this issue has been solved somewhere or if someone has come up with a better practice that I haven't stumbled across yet. Here's a link to the multiple process issue discussion: Problem with Python logging RotatingFileHandler in Django website I also tried extending the RotatingFileClass as shown by this article but it didn't solve my problem: Does python logging.handlers.RotatingFileHandler allow creation of a group writable log file? Here's my logging config: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s", 'datefmt' : "%d/%b/%Y %H:%M:%S" }, … -
Django taggit Tags and Tag Count based on filters applied on Model
I have BlogPost model with category and other fields and also tags(using django-taggit). Now below are my sample objects. o1 = BlogPost(category='c1', title='some title') o1.tags.add('tag1', 'tag2', 'tag3') o1.save() o2 = BlogPost(category='c1', title='some title') o2.tags.add('tag1', 'tag2') o2.save() o3 = BlogPost(category='c2', title='some title') o3.tags.add('tag1', 'tag2', 'tag3') o3.save() Now I want to get most common tags of blogpost based on category, like category c1 having tag1, tag2 as most common and counts are 2,2. So I have used BlogPost.tags.most_common().filter(blogpost__category='c1').annotate(tag_count=Count('name')). Its getting tag1, tag2 but counts are multiplied. How to make a query for this scenario. -
How to show summary of a content (CKEditorField)?
I have a model in which I have made a field 'content' which is a RichTextUplodingField() , Now I have a homepage in which I want to display all the blogs written. Basically I want to have title, summary with the image (which I used in RichtextUplodingField) of each blog posted so that I can redirect to the full content as soon as someone clicks "ReadMore". I know how to create summary in CharField, but don't know how can this be possible with RichTextUploadingField. I'm currently using seperate field for "Summary" and "Image", that I use for summary creation. I know there might be some other way to do this, a better way. Kindly help me with this problem. Here is my model. class ArticleModel(models.Model): title=models.CharField(null=False,default='Placeholder',max_length=250) author=models.ForeignKey(User,on_delete=models.SET_NULL,null=True) content=RichTextUploadingField(default="Add the content here") summary=RichTextField(default="Enter the summary here...") slug=models.SlugField(max_length=250,null=False) published_at=models.DateTimeField(auto_now_add=True) image=models.ImageField(upload_to='images',blank=True,null=True) tags=TaggableManager() class Meta: ordering=['-published_at'] def __str__(self): return self.title def save(self,*args,**kwargs): self.slug=slugify(self.title) super(ArticleModel,self).save(*args,**kwargs) -
I want to upgrade this project so it shortens multple URL at the same time
Link to my github repo Can anyone take a look at it and tell me changes I need to make? I want to click at the '+' button and add array to form a list and pass each url to backend one by one so that it can be shortened. I tried but I am totally new so please don't judge or downvote this. -
django filter values_list
I have a checkbox where I am selecting variables for django filter values. I am getting the values correctly so if I replace *values with pfast_type[0] or pfast_type[1] it works fine. But What I want to do is that if I select 3 variables checkbox I want this entered like pfast_type[0], pfast_type[1] and pfast_type[2] if I select one 1 variable it should be only pfast_type[0] for the values. Where am I doing false ? maybe I am searching false but I searched and couldn't find any reference information within the stackoverflow. pfast_type = request.GET.getlist("pfast_type") elif pfast_type and items: for pfast_type in range(len(pfast_type)): values= values.append(pfast_type[i]) object_list = FP.objects.filter(pk__in=items).values('RFP_Item',*values) -
Build UI for API's Json
I have an API service which gives Json data. I wanted to test that API using many different inputs. I know about other tools like Django which helps to build UI. But it takes time to learn and build my UI. Is there any tool where I can build a rapid UI using that tool to look over my Json data and analyze easily. -
Django custom form validation via POST
Description When I submit a form from front-end, my back-end works, but I can't get foreignkey by my forms.py. I'm confused since there is a result in queryset. But the form still throw the errors : uploader & course is required <QuerySet [<User: sth>]> <QuerySet [<CourseInformation: sth>]> Code forms.py class CourseFileForm(forms.ModelForm): class Meta: model = CourseFile fields = ('uploader', 'course', 'cfile', 'cfile_class', 'cfile_year', 'cfile_content') def __init__(self, *args, **kwargs): username = args[0]['username'] course_id = args[0]['course_id'] super(CourseFileForm, self).__init__(*args, **kwargs) if username: self.fields['uploader'] = forms.ModelChoiceField(queryset=User.objects.get(username=username)) print(User.objects.filter(username=username)) if course_id: self.fields['course'] = forms.ModelChoiceField(queryset=CourseInformation.objects.get(pk=course_id)) print(CourseInformation.objects.filter(pk=course_id)) views.py if request.method == 'POST': form = CourseFileForm(request.POST) if form.is_valid(): form.save() return redirect('courses_detail', id=id) print(form.errors) return render(request, 'courses/upload.html', {'course': course, 'form': form}) models.py class CourseFile(models.Model): uploader = models.ForeignKey(User, on_delete=models.DO_NOTHING) course = models.ForeignKey(CourseInformation, on_delete=models.CASCADE) ... -
how to make for loop work faster in python
I am comparing each description with dataframe value but its taking more time. for value in desc: if ' ' in value: splitedwords = value.lower().split(" ") finallist = [''.join(k) for i in range(len(splitedwords)) for k in splitedwords[i:i + 2]] match1 = df.value.str.lower().isin(finallist) if df[match1].variable.any(): categorylist.append(value + ":" + df[match1].variable.astype('str')) else: match = df.value.str.lower().isin(splitedwords) if df[match].variable.any(): categorylist.append(value + ":" + df[match].variable.astype('str')) else: categorylist.append(value + ":" + defaultValue) else: match3 = [listva for listva in dfvaluelist if listva in value.lower()] for a in match3: idx = df.value.str.contains(a) categorylist.append(value + ":" + df[idx].variable.astype('str')) print(categorylist) i have a list of desc as desc= ['POS TXN AT MOTHERCARE M', 'POS TXN AT BARBERIA M', 'POS TXN AT BATELCO M', 'POS TXN AT RUYAN PHARMACY M', 'POS TXN AT MEGAMART EXPRESS M', 'POS TXN AT HOURS MARKETS M', 'POS TXN AT TALABA T COM M', 'ATM WDR SWT AT SCBB', 'POS TXN AT RUYAN PHARMACY M', 'CDM CASH DEPOSIT AT', 'IBANKING CREDIT CARD PAYMENT', 'POS TXN AT MONO BISTRO RESTAURANTM', 'POS TXN AT RUYAN PHARMACY M', ' POS TXN AT RUYAN COLD STORE M', 'POS TXN AT BABEL M', 'ATM WDR SWT AT SCBB', 'POS TXN AT DAY AND NIGHT MARKET J', 'POS TXN AT HOME …