Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Appending the Request URL with base url in python django
enter image description here This is exactly the same error i get when i click on user to do an update. Am not sure what's going on wrong here. This is my first post in StackOverFlow, let me know if I need to post some more details. Like the url.py and admin.py and router.py -
How can I get a full dict when I have performed a Many-to-one relationships?
class EbConfig(models.Model): id = models.IntegerField(primary_key=True) specific_field_config_id = models.IntegerField() judge_result = models.CharField(max_length=50) class EbResult(models.Model): eb_config = models.ForeignKey(EbConfig, on_delete=models.CASCADE) cc_log_info_base_id = models.BigIntegerField(primary_key=True) eb_config_id = models.IntegerField() result = EbResult.objects.filter(...)... After satisfying my condition, I got a QuerySet named "result". When I input: result.select_related('eb_config').values() I get something like this: <QuerySet [{'eb_config_id': 1, 'cc_log_info_base_id': 10001},...> But what I want to get is like this: "<QuerySet [{'eb_config_id': 1, 'cc_log_info_base_id': 10001, 'id ':'', 'specific_field_config_id ':'', 'judge_result ':''},...>" What can I do to get that? I knew, I can get an object of EbConfig by: list(test)[0].eb_config But what I truely want is a full dict of EbConfig INNER JOIN EbResult. When I print result.query, I find a right SQL sentence which can successfully run in MySQL and get a result I expect. -
PasswordChangeForm with Abstractuser not responsive on submit
I have a custom user model class User(AbstractUser): company = models.CharField(max_length=30, blank=True) When I try to change my password using the ChangePasswordForm, upon submit, nothing happens. @login_required def change_password(request): if request.method == 'POST': form = PasswordChangeForm(data=request.POST, user=request.user) if form.is_valid(): form.save() update_session_auth_hash(request, form.user) return redirect('/account/profile') else: form = PasswordChangeForm(request.user) args = {'form': form} return render(request, 'accounts/change_password.html', args) This was working before with a regular usermodel hope someone can help. -
'Content-Length: 0', Javascript, XMLHttpRequest, Django REST API
I wish I can find some assistance with my code. I have set up a Database on mySQL, and connected it to Django REST. Those both work as expected, and I can access the REST with Firefox REST Client with it returning the correct tables from the database. I have started working for user interface with html and javascript and I have encountered a problem I am unable to solve. I am a student, and this is part of my school work, but unfortunately my teachers are unavailable at the moment due summer vacations and I am eager to continue my project. Hence I am askin for Your assistance. As I have tested the Django REST through Firefox REST Client, I am sure the database and REST service is not at fault so here we come to my code. I seem to be able to get connection to the REST Service, giving me code 200 and state 4 (pictures linked underneath) ReadyStateChange + ReadyState console.logs 200 OPTIONS However I am unable to pull data out, giving me 'Content-Length: 0'. Originally I thought the issue would be cross-domain request problem until my fellow student said he does not think it is, β¦ -
Successful Bitbucket pipeline despite exception in Django test
The Bitbucket pipeline finishes successfully even though there occurred an exception in a python test. Does anyone know how to make the pipeline fail in case of an exception? -
What's the most DRY way to disable a link to the current page?
In my Django web-app, I want to let users sort model objects by different parameters, which I achieve with URL parameters which tell the view which items should be loaded. Here's the Jinja/HTML snippet from the template: <p><b><span class="text-info">sort by:</span></b> <a href="{% url 'artists' %}">latest_release</a> | <a href="{% url 'artists'%}?sorted_by=name">alphabetically</a> | <a href="{% url 'artists'%}?sorted_by=next_release">soonest release</a></p> If the user is already sorting by latest_release (the first link), I want the link from it removed. However, I can't seem to find a way to do this in a DRY way. -
Jquery submit button not working in Django 2.0
I recently upgraded my project from Django 1.9.5 to Django 2.0.6. Everything seems to be working fine except the submit button of a form I'm using. HTML code for new-question.html: <form role="form" action="" method="POST" enctype="multipart/form-data">{% csrf_token %} {% with WIDGET_ERROR_CLASS='field_error' %} <p> <strong>Select the category:</strong> <img id="ajax-loader" src="{% static 'website/images/ajax-loader.gif' %}" style="display:none;"> </p> <div class="row"> {{ form.category.errors }} <div class="col-lg-3 col-md-3 col-sm-3"> {% render_field form.category class+="form-control category"%} </div> <div id = 'tutorial' class="col-lg-3 col-md-3 col-sm-3"> {% if category %} {% render_field form.tutorial class+="form-control tutorial" %} {% else %} {% render_field form.tutorial class+="form-control" %} {% endif %} </div> <div class="col-lg-2 col-md-2 col-sm-2"> <small><strong> <a id="similar-link" data-toggle="modal" data-target="#similarModal" href="#"> 0 similar questions </a> </strong></small> </div> </div> <hr> <div class="row"> <div class="col-lg-12"> {{ form.title.errors }} <div class="form-group"> <label for="id_title"><strong>Question Title:</strong></label> {% render_field form.title class+="form-control title" %} </div> {{ form.body.errors }} <div class="form-group"> <label for="id_body" ><strong>Question Description:</strong></label> {% render_field form.body class+="form-control body" %} </div> <div class="form-group"> {% block picturetitle %} <label for="id_image" ><strong>Upload a picture:</strong></label> {% endblock %} {% render_field form.image %} </div> <div class="form-group"> {% block spamCheckbox %} {% endblock %} </div> </div> </div> <script src='https://www.google.com/recaptcha/api.js'></script> <div class="g-recaptcha" data-sitekey="{{ SITE_KEY }}" data-callback="enableBtn"></div> <script type="text/javascript"> function enableBtn() { document.getElementById("submit_question").disabled = false; } function changeText() β¦ -
django orm get lastest child in annotate
django 2.0.2 python3.4 Model.py Post(model): PostUID = PK Report(model): ReportUID =PK PostUID = FK("Post") FeedBack = Boolean my orm models.Post.objects.all(). annotate(LastReportUID=Max("report__ReportUID"), ReportCount=Count("report"),FeedBack="???") if "???" to use report__FeedBack return Duplicate Post i want one Post is return One raw how to have lastest Report FeedBack in the "???" -
Django and travis CI secret key error with travis encode environment variables
I have a Django project that is setup to keep SECRET_KEY out of settings.py by setting my environment variable and then using the os.environ['SECRET_KEY']. I also use travis ci secure encrypted environment variables in order to have my SECRET_KEY for my django project accessible for travisci to use. The travisci builds successfully on my github account. However, travisci build will fail on anyone else who forks the code when trying to run python manage.py migrate/test with this error: SECRET_KEY = os.environ['SECRET_KEY'] File "/home/travis/virtualenv/python3.6.3/lib/python3.6/os.py", line 669, in __getitem__ raise KeyError(key) from None KeyError: 'SECRET_KEY' In the settings.py I have this line: SECRET_KEY = os.environ['SECRET_KEY'] The .travis.yml file looks like this: language: python python: - 3.6 env: global: - secure: # encrypted string for SECRET_KEY - secure: # encrypted string for another settings KEY - secure: # encrypted string for another settings KEY install: - pip install -r requirements/requirements.txt script: - flake8 --count --quiet - python manage.py migrate --run-syncdb - python manage.py test Does anyone know if there is an issue with creating encrypted travis ci env variables and having others fork the code to also use those? I can't figure out why it works for me and doesn't work at all β¦ -
Method generating "Change History" in model.save not working as expected
I have a class Account which represents a customer in my application. I want to track all the changes to an Account by logging them into my database. An example of what I want to achieve: User A changed Account.is_abandoned from False to True To do so, I created a class Entry which can be thought of as log entry to store the block quote above. I am trying to incorporate this recipe def save(self, *args, **kwargs): """Overriding this to create an Entry in the corresponding Timeline. Pass in user=User for Entry Creation. See this link for the recipe. """ old = type(self).objects.get(pk=self.pk) if self.pk else None user = kwargs.pop('user', None) super().save(*args, **kwargs) if not old: return changes = {} for attr in ['instance', 'status', 'spent_in_hkd', 'is_attention_required', 'is_abandoned', 'is_spending']: if getattr(old, attr) != getattr(self, attr): changes[attr] = (getattr(old, attr), getattr(self, attr)) if not changes: logging.debug('EntryNotCreated: No changes detected.') return cs = '\n'.join(['{}: {} -> {}'.format(k, v1, v2) for k, (v1, v2) in changes.items()]) entry = Entry.objects.create( user=user, account=self, content=cs ) entry.save() My question is that sometimes this method doesn't detect any changes even though I changed it via Django's generic UpdateView. Any ideas why? -
Pass coordinates (google maps API) React to express mongodb
greetings. (Sorry for my bad English)... I have a question that I hope you will help me solve, it is about how to pass the coordinates of an address taken from the Google maps API with React.JS in the Frontend and pass those coordinates to MongoDB and thus show the administrator the client's address. What are your recommendations? I had planned to use the Stack MERN or Stack MEVN I also want to know if it is more feasible to use a relational or non-relational database (MariaDB or MongoDB). I have more experience in Python and Django but not to such a degree to be able to develop that project (Backend) and I found more resources to learn with Javascript (Node.js and express). I would like to know the opinions of more experienced people like you. -
Connecting two apps models by using foreign keys Django
I'm super new to Django. i have a problem with connecting two models from different apps to each other .... app A it must be connected to app B by using foreign key ... I tried this import but not working from A.models import ClassNamme i get this error: **ERRORS:** user_profile.Orders.fk_cadfile: (fields.E304) Reverse accessor for 'Orders.fk_cadfile' clashes with reverse accessor for 'Orders.fk_product'. HINT: Add or change a related_name argument to the definition for 'Orders.fk_cadfile' or 'Orders.fk_product'. user_profile.Orders.fk_product: (fields.E304) Reverse accessor for 'Orders.fk_product' clashes with reverse accessor for 'Orders.fk_cadfile'. HINT: Add or change a related_name argument to the definition for 'Orders.fk_product' or 'Orders.fk_cadfile'. -
You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings
"django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings." Guys this thing is coming when I run the code in "Pycharm".So,if anyone you have figured it out,pls!!! answer it ASAP.Below is the output of program: "C:\Program Files\JetBrains\PyCharm 2018.1.4\bin\runnerw.exe" C:\Users\DELL\PycharmProjects\Django1\venv\Scripts\python.exe C:/Users/DELL/Desktop/nucleus/manage.py runserver 8000 Traceback (most recent call last): File "C:/Users/DELL/Desktop/nucleus/manage.py", line 15, in execute_from_command_line(sys.argv) File "C:\Users\DELL\PycharmProjects\Django1\venv\lib\site-packages\django\core\management__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Users\DELL\PycharmProjects\Django1\venv\lib\site-packages\django\core\management__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\DELL\PycharmProjects\Django1\venv\lib\site-packages\django\core\management\base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\DELL\PycharmProjects\Django1\venv\lib\site-packages\django\core\management\commands\runserver.py", line 61, in execute super().execute(*args, **options) File "C:\Users\DELL\PycharmProjects\Django1\venv\lib\site-packages\django\core\management\base.py", line 335, in execute output = self.handle(*args, **options) File "C:\Users\DELL\PycharmProjects\Django1\venv\lib\site-packages\django\core\management\commands\runserver.py", line 70, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "C:\Users\DELL\PycharmProjects\Django1\venv\lib\site-packages\django\conf__init__.py", line 56, in getattr self._setup(name) File "C:\Users\DELL\PycharmProjects\Django1\venv\lib\site-packages\django\conf__init__.py", line 41, in _setup % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Process finished with exit code 1 -
django timezone read model data wrong?
i have a django app, when i use python manager shell to read model data, something go wrong. 1.in setting.py the code like this: LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Shanghai' USE_I18N = True USE_L10N = True USE_TZ = True In shell could not read data: In [6]: Post.objects.all() Out[6]: <QuerySet [<Post: china 2018-06-13 00:54:09+00:00>, <Post: hello 2018-06-12 09:32:23+00:00>]> In [7]: Post.objects.filter(publish__year="2018", publish__month="6") Out[7]: <QuerySet [] change USE_TZ = False in setting.py file. LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Shanghai' USE_I18N = True USE_L10N = True USE_TZ = False In shell could read data: In [2]: Post.objects.all() Out[2]: <QuerySet [<Post: china 2018-06-13 00:54:09>, <Post: hello 2018-06-12 09:32:23>]> In [3]: Post.objects.filter(publish__year="2018", publish__month="6") Out[3]: <QuerySet [<Post: china 2018-06-13 00:54:09>, <Post: hello 2018-06-12 09:32:23>]> -
Django register form error
I created a custom user model to register people for my site. Everything is operating, however when I press submit on my register page to create a user, I get the error "super(type, obj): obj must be an instance or subtype of type". I assume it's from my forms.py, StudentSignUpForm, def save where user = super(UserAdminCreationForm, self).save(commit=False), because when I comment it out the error is gone. Why is this issue occurring. Thanks for helping me on my journey of learning :) models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.contrib.auth.models import User from django.contrib.auth import get_user_model class UserManager(BaseUserManager): def create_user(self, first_name, last_name, email, password=None, active=True, staff=False, admin=False): #add other arguments that are required fields if not email: raise ValueError("Users must have an email address") if not password: raise ValueError("Users must have a password") if not first_name: raise ValueError("Users must have a first name") if not last_name: raise ValueError("Users must have a last_name") user_obj = self.model(first_name=first_name, last_name=last_name, email = self.normalize_email(email)) # add arguments full_name=full_name user_obj.set_password(password) user_obj.staff = staff user_obj.admin = admin user_obj.active = active user_obj.save(using=self._db) return user_obj def create_staffuser(self,first_name, last_name, email, password=None): #add arguments user = self.create_user(first_name, last_name, email, password=password, staff=True) return user def create_superuser(self, first_name, last_name, β¦ -
Django ORM's N+1 Issue
I'm designing an endpoint on DRF that returns a list of Rides. Each Ride has a many-to-one relationship with Bookings meaning each ride can have many bookings. I have a requirement to return a reverse relationship, Bookings, with each Ride object returned. The scenario above creates the classic n+1 ORM issue which has been discussed in many places around the web. To combat this issue I created a test endpoint (see below) that used the prefetch_related method in the query. This does help reduce the number of queries however I'm still seeing some very odd query behavior in my sql logs. Here's my endpoint: class ListRidesTest(APIView): permission_classes = (permissions.AllowAny,) def get(self, request): rides = Ride.objects.prefetch_related('bookings') serializer = RideSerializer(rides, many=True) return Response(serializer.data, status=status.HTTP_200_OK) My RideSerializer: class RideSerializer(serializers.ModelSerializer): bookings = BookingItemSerializer(read_only=True, allow_null=True, many=True) class Meta: model = Ride fields = ('id', 'name', 'description', 'capacity', 'is_active', 'bookings') And the BookingItemSerializer: class BookingItemSerializer(serializers.ModelSerializer): class Meta: model = Booking resource_name = 'bookings' fields = ('id',) I have five Ride objects in my database that have many-to-one relationships with 212 Booking objects. What's a bit troubling is that prefetch_related doesn't seem to be doing a join with the bookings model and Django then queries one Ride β¦ -
Django: Testing Post View
I'm trying to test my post with a testing suite. I've just been trying to follow the documentation to do this. The main problem I'm having right now is that response.context is returning None. This is what my test class looks like: class JSONHandlerTester(TestCase): def setUp(self): self.client = Client() self.jsonTestPath = os.path.join(settings.MEDIA_ROOT,'json','jsonTests') def testing(self): for test in os.listdir(self.jsonTestPath): testFile = os.path.join(os.path.join(self.jsonTestPath),test) split = test.split('.') testName = split[0] testNameArray = re.findall('[a-zA-z][^A-Z]*', testName) project = testNameArray[0] team = testNameArray[1] with open(testFile) as json: response = self.client.post('/JSONChecker', {'json_project': project, 'json_team': team, 'json': json}) print response print response.context if (response.context['title'] == "Congratulations!!! Your JSON Passes!!!" and testNameArray[2] == "Pass") or (response.context['title'][2:] == "The" and testNameArray[2] == "Fail"): print test+': Works' else: print test+': BREAKS: PROBLEM DETECTED' Also this is what my render looks like: return render(request, 'JSONChecker.html',context = {'title': title, 'validationErrors':validationErrors,'errors':errors, 'isLoggedIn':isLoggedIn, 'form': form, 'post':post}) If the form is invalid or the extension isn't json this is what the render looks like (this shouldn't be triggered by suite): return render( request, 'JSONChecker.html', context = {'title': title,'errors': errors,'isLoggedIn':isLoggedIn,'team':team, 'email':email,'form':form, 'post': post}, ) I'm using Django 1.11 and Python 2.7 -
How to add data to database and show on admin page with calculation
From Django.db import models Class multi(models.Model): Varone = models.Integer() Vartwo = varone * 2 How to do calculations in this class and show that calculations in the admin page of Django. I tried to Google couldn't find answers, sorry I am new to programming. Thank you -
Django: Redirect if the link doesn't match urlpatterns
How do I make django to redirect from www.example.com to www.example.com/home ? Below you can see my urlpaterns and I'm using url(r'', RedirectView.as_view(pattern_name='home', permanent=False))to redirect to my /home page but when it detects a link without / at the end it redirects me to the /home page. Sorry if my english is bad :)) urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^home/', views.home, name="home"), url(r'^surukkam/$',views.shrink,name="surukkam"), url(r'^(?P<inputURL>[0-9a-zA-Z]+)/$',views.retrieve,name="virivu"), url(r'', RedirectView.as_view(pattern_name='home', permanent=False)) ] -
Serializer look_up
I'm trying to send the following HTTP Post API request to create a new EventInterest object. How can I accomplish this in a smallest payload instead of sending the entire object? I'm attempting an extra layer of security-through-obfuscation and instead of using the default integer pk, how can I use uuid for Event and username for User? .... Or do the extra SQL lookups negate the benefits of simplifying the payload and I should just use pk? models.py class Event(models.Model): name = models.CharField(max_length=255) description = models.TextField(max_length=500) uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, db_index=True, blank=True) class EventInterest(models.Model): event = models.ForeignKey(Event) sender = models.ForeignKey(settings.AUTH_USER_MODEL) # from User api.py class EventInterestViewSet(mixins.CreateModelMixin, GenericViewSet): queryset = models.EventInterest.objects.all() serializer_class = serializers.EventInterestSerializer lookup_field = 'uuid' On the serializer.py end I've tried SlugRelatedField, SerializerMethodField. HTTP Post: { "event": "da9290c6-f6f8-4d27-bfe0-d388ed911fe8", "sender":"eX8gkxJNDREv" //this is the username field } -
Unable to reference database model in the template
I am passing the 3 DB reference in my template out of which I can only use two using Jinja. views.py def post(request, foo, bar): print("reached here", foo, bar) query = Blog.objects.all().filter(category=foo, slug=bar) return render(request, 'blog/post.html', {'query': query, 'code': code_view, 'category': category_view}) post.html <div class="container"> {% for i in query %} {{ i.title }} {% endfor %} {% for i in code %} <code class="fa-code-fork">{{ i.codeblock_one }}</code> {% endfor %} </div> I am able to get an output from i.codeblock_one but not i.title, I have no idea why. -
Python Subprocess with ffmpeg & django file (video) object thumbnail generation error
I am trying to re-write the currently outdated easy-thumbnails-ffmpeg and have made some progress. However, I am currently getting the error "no such file or directory" when attempting to send a stream of bytes (mp4 video) into ffmpeg, a frame at 00:01 to an image and output it as a stream of bytes. from PIL import Image from subprocess import Popen, PIPE from django.utils.six import BytesIO def ffmpeg_frame(source, frame='00:00:01', **options): if not source or not source._file: return source._file.seek(0) cmd = ['ffmpeg','-i','-f','h264','-','-ss',frame,'-vframes','1','-f','image2' ,'-'] data = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE).communicate(source.read()) print('Output:', data) if not data[0]: return image = Image.open(BytesIO(data[0])) image.load() return image I'm unsure if the issue is to do with my use of ffmpeg flags or how I am piping in/out byte data. When placing the flags '-f','h264' before '-i', I also get the following error: Error while opening decoder for input stream #0:0 : Invalid data found when processing input -
Django Forbidden 403 Error "CSRF token missing or incorrect" when trying to log in when already logged in
So I am using all built in Django, I don't have my own login view. First I'll describe how the scenario is created that causes this error: So someone is logged in and has multiple tabs open and then they log out. Eventually the other tabs will be directed to the accounts/login page either by themselves or the page is refreshed or a link is pressed, it doesn't really matter how. The point is this person now has multiple tabs that are all on the accounts/login screen and no one is authenticated/logged in. So then this person successfully logs in in one of the tabs. They then go and to one of the other tabs, which are still on the accounts/login page (even though a session is already created). If this person then tries to log in as the person logged in, or really anyone, in fact even if the username and password are empty and they simply click the login button, the 403 Error CSRF token missing or incorrect gets thrown. (I hope this makes sense) Anyways, how can I fix this? And this is my html template if that helps: {% extends 'base.html' %} {% load crispy_forms_tags %} β¦ -
multiple select in select django orm
I need make this stament throw ORM in Django, but idk how to make it. SELECT table_1.id, (SELECT COALESCE(SUM(qty_1), 0) FROM table_2 WHERE table_2.fk = table_1.id AND date BETWEEN start_date AND end_date), (SELECT COALESCE(SUM(qty_2), 0) FROM table_2 WHERE table_2.fk = table_1.id AND date BETWEEN start_date AND end_date), (SELECT COALESCE(SUM(qty_3), 0) FROM table_2 WHERE table_2.fk = table_1.id AND date BETWEEN start_date AND end_date) FROM table_1 Any suggestion would be appreciated. Plz help me, I tried find this question here without any luck. -
Static CSS files with Django Application Error
I am trying to add a css file to my Django app, eventually in production but right now I can't even get it to run the local server using runserver. Whenever I load the page that should use the css file, I get the error "GET /static/ldap/style.css HTTP/1.1" 404 1666, with some variation on the filepath and error code, as I have tried a whole lot of combinations. Some other errors that I have gotten are "GET /static/style.css HTTP/1.1" 404 1651 Not Found: /ldap/style.css [12/Jun/2018 15:07:07] "GET /ldap/style.css HTTP/1.1" 404 2804 My current setup is attempting to copy the official docs from the tutorial and the suggested doc in the settings.py file. I have: in my settings.py: STATIC_URL = '/static/' , in my search.html: {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'ldap/style.css' %}"> And the file structure of my project root folder is thus (I am trying to implement this in the ldap application, to be clear): βββ conf βββ db.sqlite3 βββ djangoWrapper β βββ __init__.py β βββ __pycache__ β βββ settings.py β βββ templates β β βββ djangoWrapper β β βββ index.html β βββ urls.py β βββ views.py β βββ wsgi.py βββ ldap β βββ admin.py β β¦