Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django force migrations/database syncing
I had my migrations file in version control, and it went out of sync between production and development (I know, that was the mistake, but it's happened now). As a result, I couldn't run migrations in production. I deleted the migrations folder, and then re-ran makemigrations and migrate. makemigrations logs out creating all the fields. However, migrate simply says "no migrations to apply", and the extra fields do not appear in the database. All I've changed is adding nullable fields to a model, so it should be a straightforward migration. I can drop the whole db and start over, but I'd prefer not to because it takes a long time to re-populate. Is there a way that I can force Django to find the differences between the DB and the models, and build the correct migrations to add the fields? I attempted adding nonsense models to try and trigger a refresh. But that hasn't changed anything. -
Convert Image File Object to File Object in angular 6
i'm getting image object with url address which by calling angular httpClient.get(). I stuck here about to convert image object to file object -
Template tag for going from model1 to model2 that has foreign key to that model1
Is there a template tag or a way that I can go from my main model to a specific model that has a foreign key to my main model? models.py class BillingAddress(models.Model): user = models.ForeignKey(UserCart, on_delete=models.CASCADE) address1 = models.CharField(max_length=120, null=True) class HomeAddress(models.Model): user = models.ForeignKey(UserCart, on_delete=models.CASCADE) address1 = models.CharField(max_length=120, null=True) class UserCart(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default=None) I want to get the 'address1' field from the BillingAddress that is related to a usercart. I don't think that I can use {{usercart.address1}} as both HomeAddress and BillingAddress have a field called address1 and are related to the usercart. Thanks! -
How to track requests in Django with an ID integer?
I develop an Django application in which when the user makes a POST, it creates some .txt files in the server. All txt files that are created in a request, have the same ID integer in their name in order to differentiate among the requests. For example: with the first POST --> 1_file.txt with the second POST --> 2_file.txt To succeed that every function in my server code (views.py or utils.py) that creates a txt file have a function_name.counter variable to keep track the times that each function runs (by the users' POSTs): def getEmail(email): getEmail.counter += 1 with open(BASE_DIR + str(getEmail.counter) + "_Email.txt", "w") as f: f.write('%s' % email) getEmail.counter = 0 But that way is such an error prone and with the apache's restart all .counter change to zero. Is there a more efficient way to succeed that ? -
How to fix "undefined" JSON response sent from Python to Javascript
I'm writing a web app for my personal website using "Django". The app is a "python script" that responds to a "javascript script" with JSON data, but I get "SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data". I have no errors in the code. I tried the following answers: how to fix undefined data from json data? JSON property returning undefined -The Python script: #!/bin/python3 from django.http import JsonResponse return JsonResponse({'foo':'bar'}) -The JAVASCRIPT: $.ajax({ type: "GET", url: '{% static 'location_json.py' %}', success: callbackFunc }); function callbackFunc(response) { // do something with the response console.log(response.foo); } Actual results are "undefined". Expected results is the word "bar". -
Django: migration inserts data into a wrong db (when running tests)
I have a rather simple migration that creates a table and then populates it with some initial data. Everything works fine when I run the migrations in 'normal' mode. However, when I run tests, the test runner creates a separate db for tests (say, test_my_default_db), this migration creates the tables in the test database, but the data is then written to the default db (my_default_db). The function that is run for inserting the data accepts schema_editor, but I couldn't find how to use it to run python database code as opposed to raw SQL. Here is a gist of the migration: def load_init_data(apps, schema_editor): MyModel = apps.get_model("my_app", "MyModel") items = [...] for item in items: MyModel.objects.create(**item) class Migration(migrations.Migration): dependencies = [...] operations = [ migrations.CreateModel(name='MyModel',...) migrations.RunPython(load_init_data, delete_init_data) ] How can I make sure that the data is written to the test database instead of the default database? -
How can I use rest_framework.authtoken without create table authtoken_token in Django
When I added rest_framework.authtoken and used Token.objects.get_or_create(user = user) for check auth call API, django request must create table authtoken_token in DB, but customer don't want add new table in DB. So, have any way resolve it? Thanks for your time!!! -
Django Template filtered on clicked variable
Take the following Models: class InsName(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=30, verbose_name = "Insurer/Broker") def __str__(self): return self.name class Development(models.Model): id = models.AutoField(primary_key=True) logno = models.CharField(max_length=13, unique=True) insurer = models.ForeignKey(InsName, on_delete=models.SET_NULL, null=True, blank=True) Phase_status = ( ('dev','Development'), ('review','Review') ) phase = models.CharField(max_length=10, choices = Phase_status, default='review', ) user = models.ForeignKey(User, on_delete=models.CASCADE) date_added = models.DateField(default=datetime.date.today) comments = models.TextField(max_length=350) def get_absolute_url(self): return reverse('development-detail', args=[str(self.id)]) def __str__(self): """String for representing the Model object.""" return f'{self.id} ({self.insurer})' I have a template that outputs a table of the Developments. What i want is when an 'Insurer' is clicked it brings up a template of all the developments filtered for that selection. I've been trying various things but I don't know how to get the variable 'Insurer' name into the view: def insurer_filter(request): ins_name = InsName.objects.filter(insurer= {{ value }}) return render(request, 'insurer_filter.html', context = ins_name) Please forgive my dodgy coding (or any advice is helpful!). I'm completely new to this and just finding my feet but I cant find any help on doing the above. -
can set up the Database in Django
Django uses SQLite by default; it is easy for Django users as such it won’t require any other type of installation. In the case your database choice is different that you have to the following keys in the DATABASE ‘default’ item to match your database connection settings. -
serializer.save() not saving in django rest
I am having a problem with my APIView for reading and writing names of places. Here is my view, class pList(APIView): def get(self,request): e = placename.objects.all() ser = placeSerializer(e,many=True) return Response(ser.data) def post(self,request): serializer = placeSerializer(data=request.data, many=True) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) and my serializer class placeSerializer(serializers.ModelSerializer): class Meta: model = placename fields = ('em_name') the get method works fine but when i try to POST, i get an empty set([]).What am i doing wrong here? PS: I am new to DRF. -
filter object which begin by string in a list
Here is my code : communeList = [ "78", "95", "77", "91", "92", "93", "94", "75", ] commune_list_1 = list(Commune.objects.all()) commune_list = [] for c in commune_list_1 : if c.codePostal[0:2] not in communeList : commune_list.append([c]) CodePostal is a charfield with 6 characters and i would like a query to return me all the codepostal which begins (the first 2 characters) by the element of the list communeList. Regards -
why im unable to authenticate other users except the super user in django?
I have used the default path('',include("django.contrib.auth.urls")) in django to perform login,password reset operations for my project,i have thoroughly checked my signup form and the database,everything goes well with the registration part,but i'm unable to authenticate all other users except the super user,what might be the reason for this issue? -
Django PasswordResetView - Gmail email is not sending
I setup a PasswordResetView with a template that has a submit button, I also setup the necessary configuration for sending using a Gmail account but then when I try to send a password reset to an email, the console returns a 302 response and no email is received. I already allowed less secure apps in my gmail account, but it still doesn't send any email. Below are the details of my setup. URL: path('password-reset/', auth_views.PasswordResetView.as_view(template_name='users/password_reset.html'), name='password_reset'), settings.py: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'my@gmail.com' EMAIL_HOST_PASSWORD = 'mypass' Reset Password Template: {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4 pb-2">Reset Password</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Request Password Reset</button> </div> </form> </div> {% endblock content %} Server Response: -
SES emails are getting timed out on AWS Lambda
I have deployed a Django app on AWS lambda using Zappa. But I cannot send emails using AWS SES. It is always getting timed out. My lambda function is inside a VPC. It can access the RDS instance without any problem. -
Djanglo Logger not writing INFO level logs on server. (Works fine on Localhost)
I am using Django Logger to auto-write logs to file. My application is based on Django Rest Framework, so I want status of every request to be logged in a file. This is my settings.py file: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'simple', }, 'file': { 'level': 'INFO', 'class': 'logging.handlers.RotatingFileHandler', 'filename': os.path.join(BASE_DIR, '../logs', 'pt.log'), 'formatter': 'verbose', 'maxBytes': 1024*1024*5, # 5 MB 'backupCount': 5, }, 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'INFO', 'propagate': True, }, 'core': { 'handlers': ['console', 'file'], 'level': 'INFO', 'propagate': True }, 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, }, } DEBUG = True Wit this setting, my local pt.log files show exactly what I need. INFO 2019-01-25 13:58:22,04872 basehttp 26474674 139808464443811584 "GET /api/v1/test/157/ HTTP/1.1" 200 935 INFO 2019-01-25 13:58:22,042 basehttp 26474 139808443811584 "GET /api/v1/test/157/ HTTP/1.1" 200 935 INFO 2019-01-25 13:58:23,311 basehttp 26474 139808443811584 "GET /api/v1/dummy/data HTTP/1.1" 200 13764 INFO 2019-01-25 13:58:23,311 basehttp 26474 139808443811584 "GET /api/v1/dummy/data HTTP/1.1" 200 13764 But when same settings are deployed on server, … -
Django mysql strange id generation
I use django to connect to mysql database. My model is like this: class MyModal (models.Model): unit = models.CharField(blank=True, max_length=500) name = models.CharField(blank=True, max_length=500) I add object to my table using this script: myModal = MyModal() myModal.unit = unit myModal.name = name myModal.save() I notice that mysql generated strange ids like this: 1, 21, 31, 41,... 91, 101, 111. I expect the ids will be 1, 2, 3, 4, ... 9, 10, 11 Any idea what caused this strange behavior? -
How can I face Invalid filter: 'has_group' error in custom django templatetags
Despite the fact that I have created a templatetags folder and put in __init__.py the code below, from django import template from django.contrib.auth.models import Group register = template.Library() @register.filter(name='has_group') def has_group(user, group_name): group = Group.objects.get(name=group_name) return True if group in user.groups.all() else False I still facing the error "Invalid filter: 'has_group'". I want based on a specific group that I have created in admin to give access to certain functions. This is an example of my template. {% if request.user|has_group:"operationalusers" %} <div class="col-md-12"> <h1>Warehouse</h1> <div style="margin: 0 auto; text-align:center; padding:1em;"> <a href="{% url 'warehouse_stuffing_new' %}"> <button class="btn btn-success" type="">New Entry to warehouse</button></a> <a href="{% url 'upload_csv' %}"> <button class="btn btn-success" type="">Bulk Entry to warehouse</button></a> </div> {% endif %} The Traceback stack gives an error to the return line of code in my views.py def warehouse_stuffing_list(request, template_name='warehouse/warehouse_list.html'): products_with_serial_numbers = ProductSerialNumbers.objects.all() data = {} data['object_list'] = products_with_serial_numbers return render(request, template_name, data) What I miss? -
Changing the language on the page does not reflect the language in the menu
If I change the language on the page, the menu remains unchanged, while the language is translated in other places. This problem comes up if prefix_default_language=False in urls.py Has anyone had similar experiences? Thanks in advance. -
Get all Objects one by one but in a random way
Here is the code from an other post : from random import randint count = article.objects.all().count() random_index = randint(0, count - 1) all_articles_query = article.objects.all() article = all_articles_query[random_index] but now i would like to remove article from the list all_articles_query, and multiple time. I would like to sort a list of article then a random article and each time i sort a random article to move it from the list of article. I would like to get all article one by one but in a random way. Regards -
Docker, SELinux and MCS: allow container to access files created by another container in the same volume
I have two containers that share the same volume mount and the reason behind it is that I want Django uploads to be served by a reverse proxy (nginx). A user/admin will upload a file through Django (i.e. django handles the saving to MEDIA_ROOT). MEDIA_ROOT points to a volume that is mounted like so: ./assets:/assets:z According to Docker, the lowercase z flag "indicates that the bind mount content is shared among multiple containers". However, all my uploads have the following SELinux context: system_u:object_r:container_file_t:s0:c156,c725 Notice the compartments that are added to the user-uploaded file. This prevents my other container, that runs as a reverse proxy, from accessing the file (nginx returns a 403 error). May I know if there is a way to disable this container flag when a container process adds a file to a shared volume? -
How come the context of my form.py is not showing up?
I have had the same problem for quite some time and have been trying different solutions but nothing is working. I have seen different examples here on the website, but most of them are addressing older versions of Django. I have tried such solutions, but nothing is workin. The problem is as addressed by the title, " A {% csrf_token %} was used in a template, but the context did not provide the value. This is usually caused by not using RequestContext. " I have tried to add RequestContext(request) to my code instead of writing {'form': 'form'} but it didn't work out. I have tried to use HttpResponse() instead of render_to_response in my urls' views, but didn't work out as well. This is the for my original views.py before I alter anything! def ask_page_view(request): if request.method == 'POST': form = Ask_Page_Form(request.POST) if form.is_valid(): pass # does nothing, just trigger the validation else: form = Ask_Page_Form() return render(request, "ask.html", {'form': form }) This is the views.py when I have added the RequestContext() def ask_page_view(request): if request.method == 'POST': form = Ask_Page_Form(request.POST) if form.is_valid(): pass else: form = Ask_Page_Form() return renderto('ask.html', context_instance = RequestContext(request)) This is the forms.py that I am using: … -
Setting up circle ci django environment variables in config.yml file
How do I set up django environment variables for in circle ci in the config.yml file?. For instance I have environment variables DJANGO_EXECUTION_ENVIRONMENT="PRODUCTION" and DJANGO_SECRET_KEY="YOUR_SECRET_KEY_GOES_HERE". This is a sample snippet set up of the config.yml file: # Python CircleCI 2.0 configuration file version: 2 jobs: build: docker: # specify the version you desire here # use `-browsers` prefix for selenium tests, e.g. `3.6.1-browsers` - image: circleci/python:3.6.1 environment: # environment variables for primary container PIPENV_VENV_IN_PROJECT: true DATABASE_URL: postgresql://root@localhost/circle_test?sslmode=disable - image: circleci/postgres:9.6.2 environment: POSTGRES_USER: root POSTGRES_DB: circle_test working_directory: ~/accounting_api steps: - checkout - run: sudo chown -R circleci:circleci /usr/local/bin - run: sudo chown -R circleci:circleci .................. -
Django Websocket communication
I have a web application, in which i have implemented Django Channels 2 using the tutorial . The chat is working according to the tutorial. consumer.py class EchoConsumer(WebsocketConsumer): def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'power_%s' % self.room_name # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): # Leave room group async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) # Receive message from WebSocket def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] # Send message to room group async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'chat_message', 'message': message } ) # Receive message from room group def chat_message(self, event): message = event['message'] # Send message to WebSocket self.send(text_data=json.dumps({ 'message': message })) routing.py websocket_urlpatterns = [ re_path(r'^ws/power/(?P<room_name>[^/]+)/$', consumers.EchoConsumer), ] But now, i want to implement a simple python client which send messages to Django Channels application using web sockets. A simple python websocket but i am unable to connect. The error i receive is as under error ----------------------- --- response header --- [WinError 10054] An existing connection was forcibly closed by the remote host ### closed ### ----------------------- --- response header --- [WinError 10054] An existing connection was forcibly closed by the remote host ### closed ### --- request header --- GET /power/room/ HTTP/1.1 … -
how to make one models data choices for another models and how to assign id on forms.py
how to aasign id on forms.py and how to generates choices on the form of another models for individual id ,choices may be differenet for individual id class Doctor_Patient_Med(models.Model): medicines=models.CharField(max_length=1000,blank=False) comments=models.TextField(max_length=1000,blank=False) follow_up=models.DateField(null=True,blank=True) patient=models.ForeignKey(Patient) doctor=models.ForeignKey(Doctor) def __str__(self): return self.patient.name class Medical_Meds(models.Model): medicines=models.CharField(max_length=250) amount=models.IntegerField(default=0) # is_purchase=models.BooleanField(default=False) p_date=models.DateTimeField(default=datetime.now) patient=models.ForeignKey(Patient) medical=models.ForeignKey(Medical) class Medical_Meds_Forms(forms.ModelForm): patient=4, opt = [] # my = Doctor_Patient_Med.objects.all() my = Doctor_Patient_Med.objects.filter(patient=patient) for x in my: opt.append([x.medicines,x.medicines]) total=len(opt) print(total) medicines =forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=opt) amount=forms.IntegerField(label='Amount',initial="0") p_date=forms.widgets.DateTimeInput(attrs={'type':'date'}) # p_date = forms.DateTimeField(label='Purchase-Date', widget=forms.DateTimeInput(attrs={'type':'date'})) class Meta: model=Medical_Meds exclude=['patient','doctor','medical'] the problem is cannot assign id for individual user,that's why i defined patient id: patient=4 -
I need help for foreignkey queryset
I have this model class UserInfo(models.Model) : userNumber = models.CharField(max_length=15) userPin = models.CharField(max_length=7, unique=True) def __str__(self) : return str(self.userPin) class UserFollows(models.Model) : following = models.ForeignKey(UserInfo, on_delete=models.CASCADE, related_name='UserFollows.following+') followers = models.ForeignKey(UserInfo, on_delete=models.CASCADE, related_name='UserFollows.followers+') I need inner join for userPin. This command try error UserInfo.objects.filter(userPin__UserFollows__followers= '****') Unsupported lookup 'UserFollows' for CharField or join on the field not permitted.