Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Extends User Django rest framework
I would like to create a custom User in django, but i have a lot of problems. Here its mi code: models.py class Profesionales(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) dni = models.CharField(max_length=9) numColegiado = models.CharField(max_length=8) valoracionMedia = models.FloatField() numVotos = models.IntegerField() def __str__(self): return self.numColegiado, self.user.first_name Serializers.py class ProfesionalesSerializer(serializers.ModelSerializer): class Meta: model = Profesionales fields = ('numColegiado') class UserSerializer(serializers.ModelSerializer): profesionales = ProfesionalesSerializer class Meta: model = User fields = ( 'id', 'username', 'email', 'first_name', 'last_name', 'password', 'profesionales' ) def create(self, validated_data): profesional_data = validated_data.pop('profesionales') user = User.objects.create(**validated_data) Profesionales.objects.create(**profesional_data) return user views.py #Listar todos los profesionales o crear uno #profesionales/ class ProfesionalesList(APIView): def get(self, request ): profesionales = User.objects.all() profesionalSerializer = UserSerializer(profesionales, many=True) return Response(profesionalSerializer.data) def post(self, request): profesionalSerializer = UserSerializer(data=request.data) if profesionalSerializer.is_valid(): profesionalSerializer.save() return Response(profesionalSerializer.data, status=status.HTTP_201_CREATED) else: return Response(profesionalSerializer.errors, status=status.HTTP_400_BAD_REQUEST) Error!: OperationalError at /profesionales/ no such column: profesionales_profesionales.user_id Request Method: GET Request URL: http://127.0.0.1:8000/profesionales/ Django Version: 1.11.6 I'm new in django and i a bit lost!. Thanks! :) -
Django error: using a UDF inside a view model
Why do I get this error when I am trying to use get_success_url function inside the LoginView class: NameError: name 'get_success_url' is not defined views.py class LoginView(SuccessMessageMixin, FormView): form_class = AuthenticationForm template_name = 'registration/login.html' success_url = get_success_url() # url's name to redirect success_message = 'Welcome back %(username)s!' # A welcome message def form_valid(self, form): user = form.get_user() login(self.request, user) return super(LoginView, self).form_valid(form) def get_success_url(self): # find your next url here next_url = self.request.POST.get('next', None) # here method should be GET or POST. if next_url: return "%s" % (next_url) # you can include some query strings as well else: return reverse('home') # what url you wish to return -
How does Django loaddata know which fields make the natural key?
I am using Django's dumpdata to save data and loaddata to reload it. I am also using natural keys. My model looks similar to this: class LinkManager(models.Manager): def get_by_natural_key(self, url): return self.get(url=url) class Link(models.Model): objects = LinkManager() title = models.CharField(max_length=200) url = models.URLField() def natural_key(self): return (self.url, ) If I export and reimport the data, Django recognizes that the objects already exist and doesn't create duplicates. If I change the title, it correctly updates the objects. However, if I change the URL, it correctly treats it as a new object - although I forgot to mark url unique! How does it guess my intent? How does django know that my url field is the natural key? There is no get_natural_fields function. Django could call natural_key on the class instead of an instance to get the fields, but that seems really brittle: >>> [f.field_name for f in Link.natural_key(Link)] ['url'] The reason I want to know this is that I am writing my own special importer (to replace my use of loaddata), and I would like to take advantage of natural keys without hardcoding the natural key (or the "identifying" fields) for each model. Currently, I "identify" an object by it's unique … -
How can you define basic generic code blocks and insert them in other templates in Django?
I want to make my HTML site consist of single generic modules kind of like this pseudo-code. {% block body %} // Just a block inside the base html template file <div class="container_main"> {% block generic_sub_menu %} // This should be replaced with a generic submenu, which is defined in another html template file {% endblock %} Blah Blah Blah {% block generic_map_display %} // This should be replaced with a generic map display, which is defined in another html template file {% endblock %} </div> {% endblock %} So, I know how to use a base template and insert the body of a more specific template, which extends the base template. But how can I make a template which can be used everywhere with some generic HTML code which is not extending a specific template, but can be used to import some blocks of generic code by other templates? Is there a way to do this with blocks or do I have to research about some other technique in the Django Framework? -
Django - Creating a User Registration Form through a CreateView
I'm planning to create a user registration form through a CreateView. Is this possible? Here is the model: class Profile(models.Model): user = models.OneToOneField(User) favorite_food = models.CharField(max_length=100) In views: class CreateProfile(CreateView): model = Profile fields = ['user', 'favorite_food'] However, the user field only shows a dropdown box of the users. How do you make it ask for the username and password? -
Writing a GUI in HTML for a cross platform Python (Django) desktop application
I'm wanting to write a cross platform desktop application in Python, but I'm much more comfortable writing webapps using HTML, CSS, and JS, and frameworks like Django. So I'm wondering if there is any way to write a GUI for a Python desktop application as if it was a website. These are my requirements: To be able to write the front end in HTML, CSS, and JS, utilising existing libraries like Bootstrap, and AJAX To be able to write most of the backend like a traditional Django project, leveraging it's easy to use database handling. Still be able to do regular Python stuff as well (it's a P2P networking application, so I need to be able to make TCP and UDP connections, do some multithreading, etc). To be able to package it as for Mac, Windows, Linux and have the installation process as automatic as possible (no downloading of third party libraries to get my application working). I know this is a separate question, but I thought I should mention it in case any answers somehow prevent packaging my app in this way. I did find htmlPy which seems to do the first three, but it seems to be dead. … -
git add . shows 'killed 9' error when deploying in heroku
I am trying to deploy a django-app in heroku but when ever I try git add . I am getting error Killed:9 I am not understanding the error, also I tried various answers here in stackoverflow but still the results are the same. -
Error while Django form validation - TypeError: expected string or Unicode object, NoneType found
I'm testing various image uploading scenarios in an old Django installation I've got locally. While running the clean method in form validation for image uploading, I get the following error under a certain scenario: File "/home/hassan/.virtualenvs/myenv/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in get_response response = middleware_method(request, response) File "/home/hassan/.virtualenvs/redditpk/local/lib/python2.7/site-packages/newrelic-2.56.0.42/newrelic/hooks/framework_django.py", line 331, in wrapper return wrapped(*args, **kwargs) File "/home/hassan/.virtualenvs/redditpk/local/lib/python2.7/site-packages/user_sessions/middleware.py", line 46, in process_response request.session.save() File "/home/hassan/.virtualenvs/redditpk/local/lib/python2.7/site-packages/user_sessions/backends/db.py", line 73, in save session_data=self.encode(self._get_session(no_load=must_create)), File "/home/hassan/.virtualenvs/redditpk/local/lib/python2.7/site-packages/django/contrib/sessions/backends/base.py", line 86, in encode pickled = pickle.dumps(session_dict, pickle.HIGHEST_PROTOCOL) TypeError: expected string or Unicode object, NoneType found What's the sceario? I'm disallowing filesizes beyond a certain limit, raising a validation error like so raise forms.ValidationError('File too big'). I've noticed the validation error gets raised successfully most of the times, but for certain very, very big files, I instead get the error shown above. Can anyone help me get to the bottom of this? I can add more information if required. -
Django REST - Show recent posts and recently searched keywords
I will be working on the front end Vue.js using the Django REST framework. I'm trying planning and designing a web service such as a shopping mall and have not started modeling yet. Therefore, i can't attach the code. Please acknowledge it beforehand. I will ask the following questions. How to show previously-matched keywords as autocomplete below the search box? How to display the details page of a recently viewed post? Since I use the REST framework, I don't use Sessions in my Django web project, so I don't know how to store the keywords that the user has recently searched for, and how to save the most recent posts the user has seen. I need to expose the keywords that users have recently searched for in the search box, and list the posts that users have viewed recently. I wait for your advice. everybody have a good day! -
Forbidden (CSRF cookie not set.) when csrf is in header
The request header is as below. Accept:application/json, text/plain, */* Accept-Encoding:gzip, deflate, br Accept-Language:en-US,en;q=0.8 Connection:keep-alive Content-Length:129 Content-Type:text/plain Host:localhost:9000 Origin:http://localhost:8000 Referer:http://localhost:8000/ User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36 X-CSRFTOKEN:t5Nx0SW9haZTeOcErcBDtaq6psqBfeyuX4LRQ1WOOXq5g93tQkvcUZDGoWz8wSeD The X-CSRFTOKEN is there but Django still complain about CSRF cookie not set. What happen to Django? In settings.py, the naming are perfectly correct. CSRF_HEADER_NAME = "HTTP_X_CSRFTOKEN" -
validate and save in django field
I have written a function that accept as input a string and do some validation tasks on it and also changes the value. def validate(str): # do validation. If any error, raise Validation error # modify value of str return str I want to use this function as a validator for some django model field. I know how to do it. My problem is that in addition to validation I want the modified value, i.e. return value of function, to be saved in field. -
Suggest a Url pattern (to be used in django project) to match a url coming appended to my domain and send that url to my view
Can anyone suggest a django url pattern, which I can use into my project's urls.py, having such a regex to match a url . I have tried this pattern : url(r'^(?P<preurl>http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*(),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+)$',prepend_view) But this is failing on some exceptional urls.. Please take into consideration all exceptional urls too, like the following: ftp://ftp.is.co.za/rfc/rfc1808.txt http://www.ietf.org/rfc/rfc2396.txt ldap://[2001:db8::7]/c=GB?objectClass?one mailto:John.Doe@example.com news:comp.infosystems.www.servers.unix tel:+1-816-555-1212 telnet://192.0.2.16:80/ urn:oasis:names:specification:docbook:dtd:xml:4.1.2 and specially consider this one too: https://www.google.co.in/search?ei=45b1WaCFBoHpvgT7or-4CA&q=create+querydict+from+dictionary&oq=create+querydict+from+dictionary&gs_l=psy-ab.3...19031.33499.0.34313.59.47.3.0.0.0.450.6027.0j11j12j2j1.27.0....0...1.1.64.psy-ab..31.24.4689.6..0j35i39k1j0i20i263k1j0i131k1j0i13k1j0i22i30k1j33i22i29i30k1j33i21k1.297.EmAPX8QpKAw That is I, struggled escaping '?' but was unsuccessful.. Thanks Beforehand for your help.. -
True Django ORM returns empty result
I have two model classes, each containing following info. Model A latitude = models.FloatField() longitude = models.FloatField() Model B latitude = models.FloatField(null=True) longitude = models.FloatField(null=True) Now I want to filter something from model B with ModelB.objects.filter(latitude=model_a_obj.latitude, longitude=model_a_obj.longitude) which returns an empty QuerySet. The latitudes and longitudes are correct though. Because, when I do this to get the model B object ModelB.objects.filter(some_string_field="String I know by hand")[0].latitude == model_a_obj.latitude it returns True, for longitude as well True. So, why does the filter method from above return an empty result? -
How to attach csrf header and value in axios POST request
I need to send crsf token when the user sign up with form provided. However, since the signup/signin will be the first time to interact with django rest api, so I create a dummy GET request when the webpage is loaded to retrieve the crsf token from django. The token is retrieved and stored in cookie. However, I still get Forbidden (CSRF cookie not set.) from django. This is my axios POST request. import axios from 'axios' axios.defaults.xsrfCookieName = 'vcubes' axios.defaults.xsrfHeaderName = 'X-CSRFToken' let req = { url: 'http://localhost:9000/vcubes/signup/', method : 'POST', headers: { 'Content-Type': 'text/plain' }, data: data } NOTE: When I add withCredentials: true into headers in axios POST, the browser send OPTIONS request instead of POST. -
regex match words without two underscores next to each other
I want to write a regex that matches all words that contains alphanumeric characters + underscore, but not those that have two underscores next to each other! match example : 123dfgkjdflg4_, ad, 12354 not match example : 1246asd__ -
Line graph cannot be drawn accurately
Line graph cannot be drawn accurately. I wrote in views.py @login_required def result(request): return render(request, 'result.html', {'chart': _view_plot(request)}) def _view_plot(request): results = ImageAndUser.objects.filter(user=request.user).order_by('-consultation_date') scores = [100, 300, 200] dates = ['2016-04-10', '2016-10-05', '2016-10-10', '2016-10-11', '2016-12-10'] heights = [results[0].score, results[1].score,results[2].score, results[3].score, results[4].score] image_data =[] for i in range(len(scores)): if scores[i] != None : image_data.append(scores[i]) image_data.append(dates[i]) image_data.append(heights[i]) image_scores =[] image_dates = [] image_heights = [] for j in range(0,len(image_data),3): image_scores.append(image_data[j]) image_dates.append(image_data[j+1]) image_heights.append(image_data[j+2]) plt.plot(image_scores, image_heights) plt.xticks(image_scores, image_dates) jpg_image_buffer = cStringIO.StringIO() plt.savefig(jpg_image_buffer) array = base64.b64encode(jpg_image_buffer.getvalue()) jpg_image_buffer.close() return array when I read result method,line graph is drawn I really cannot understand why the order of horizontal axis is not '2016-04-10', '2016-10-05', '2016-10-10' .And I really cannot understand why graph is not line graph. How should I fix this?I think this way is for making line graph but am I wrong?What sholuld I write it? -
Django FileUploadHandler that uploads to Amazon S3
django-storages uploads into S3, but only after the entire file has been saved locally in my server. I want something else - upload the file to S3, chunk-by-chunk, without saving the entire file in my server. I can't use the AWS JS SDK, because I need to perform some calculations on the uploaded file. Thus, FileUploadHandler seems like the obvious choice - I can read each chunk, perform my calculation, push that chunk into S3 (asynchronously?), and repeat. Any implementations in existence? -
What's 'slug' for in Django?
In Django, there's slug_filed, slug_url_kwarg What is the definition of slug? I choose the more persuasive explanation within items of 3 dictionaries. In Cambridge dictionary:'a piece of metal used instead of a coin for putting in machines' In MW: 'a disk for insertion in a slot machine; especially :one used illegally instead of a coin' In Oxford:'A part of a URL which identifies a particular page on a website in a form readable by users.' They don't seem make sense. -
Deploying heroku tutorial app locally, but stuck after env file loaded
I am following the "Getting Started on Heroku with Python" tutorial, which instructs me to deploy the example django app locally. https://devcenter.heroku.com/articles/getting-started-with-python#run-the-app-locally However, the command prompt gets stuck after loading the env file and nothing happens after that even waiting for hours. My command prompt looks like this: C:\Users\arlok\python-getting-started>heroku local web -f Procfile.windows [OKAY] Loaded ENV .env File as KEY=VALUE Format The proc file contains: web: python manage.py runserver 0.0.0.0:5000 I am running this on a virtual env with dependencies installed per the instructions. Any idea on how to fix this or even troubleshoot it? -
Django apache server not stable
I have setup django with apache web server. It work but I noticed something strange. Sometimes, the page that I load working normally. Then, if I press refresh it becomes error, page not found. If I keep refreshing, sometimes it returns to normal page sometimes it becomes error. After I restart apache, it always works fine. I noticed this strange behavior appear if I tried to access some page that doesn't exist and give page not found error. Then, if I return back to the correct page, the strange behavior appears. It is as if the server or django has some cache to the error and then randomly display it. How should I handle this? -
Beginner Docker docker-compose
I'm going through this tutorial and I've successfully got the stack up and running. What's bugging me is that when I change my code (in the web service) on my host, it does automatically make the changes when I reload the page in the browser. I don't understand why it's doing that. Here's my docker-compose.yml file: web: restart: always build: ./web expose: - "8000" links: - postgres:postgres - redis:redis volumes: - ./web:/usr/src/app - ./web/static:/usr/src/app/static env_file: .env environment: DEBUG: 'true' command: /usr/local/bin/gunicorn docker_django.wsgi:application -w 2 -b :8000 nginx: restart: always build: ./nginx/ ports: - "80:80" volumes: - /www/static volumes_from: - web links: - web:web postgres: restart: always image: postgres:latest ports: - "5432:5432" volumes: - pgdata:/var/lib/postgresql/data/ redis: restart: always image: redis:latest ports: - "6379:6379" volumes: - redisdata:/data I didn't think that this was gunicorn doing the reloading because I believe gunicorn needs the --reload flag to actually do hot reloading. -
Django avoid user to go back to login page once logged in
The admin app in django has this behaviour, and I want to replicate it in my project. In the admin, once you login and press the browser back button, shows the home page again, and the it does not let you go back any further. It doesn't seem it uses javasccript. Any ideas how to accomplish this? Thanks. -
Django: How to register a user with "code" and pre_save signal
sorry if the title is not so descriptive, I did not know how to put it. I have two tables: 1.- The "Matricula" table which contains a code field and another "is_taken" field that is in "False" 2.- The "User" table and when registering a new user must insert an existing code in the table "Matricula", if the code exists then "is_taken" will be "True" and allow the user to register, my question is ... How can I do it ?, Which way would be the best? I was dealing with a "pre_save" signal but without success. models.py class Matricula(models.Model): code = models.CharField(max_length=9, blank=True) is_taken = models.BooleanField("¿Esta ocupado?", default=False) created_at = models.DateTimeField("Fecha de creación", auto_now_add = True) updated_at = models.DateTimeField("Fecha de actualización", auto_now = True) def __str__(self): return "%s" %(self.matricula) class User(auth_models.AbstractBaseUser, auth_models.PermissionsMixin): matricula = models.CharField("Matricula", max_length=9, blank=True) email = models.CharField("Correo Electrónico", max_length=100, blank=True, unique=True) first_name = models.CharField("Nombre(s)", max_length=60, blank=True) last_name = models.CharField("Apellidos", max_length=60, blank=True) is_staff = models.BooleanField("¿Es Staff?", default=False, blank=True) is_active = models.BooleanField("¿Es Activo?", default=False, blank=True) date_joined = models.DateTimeField("Fecha de registro", auto_now_add=True) Or could it be added in the views? in the process of user registration? And sorry for my bad english -
How to make Django Model run some function when create
what i want I have a column "length" in model episode ,and another have a column "sum_length" in series. i want sum_length only update when episode create, don't update when i modify it. How i do this now? now, i override the save function,and add a function call to update it, just like this. def save(self, *args, **kwargs): if not self.excerpt: md = markdown.Markdown(extensions=[ 'markdown.extensions.extra', 'markdown.extensions.codehilite', ]) self.excerpt = strip_tags(md.convert(self.description))[:54] self.series.addlength(self.video_length) super(Episode, self).save(*args, **kwargs) due to my excerpt is generate by markdown content, so i think when excerpt is blank, it's save, not update Why i ask this question ? my workaround is useable ,but i want to find a more pythonic code my workaround will not update when i really need update it. What you can give me ? maybe a sample code is fine other information Django :1.11.6 Python :3.6.3 Database: MySQL Thanks For your answer -
MSSQL with Django
I'm running Python 2.7 with Django/DRF installed on Win 10 Enterprise. My goal is to access a legacy MSSQL database that's running now on SQL Server 2017 on this machine. I've had some trouble on a couple of different tries getting Python to work with MSSQL at all, usually in some obscure error. I've gotten Django to work fine with MySQL, Postgres, and SQLite otherwise. However, this is a database that I designed many years ago when I was using .NET/MSSQL professionally, and the database is currently being used in production, and some of the clients are actually using legacy MS Access as an ADO project (cringe) to access MSSQL, so moving everything over to a different RDBMS this late in the game is not very feasible. It will create a lot more trouble than it's worth. On a side note I did some preliminary testing with .NET Core as a test for possibly using it as just a Web API server to access the DB, I was not happy with some of the movements that were done in the EF Core arena. It was very slow in my tests, and didn't support some things that I need. I wrote …