Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to deploy React and Django on OVH cloud
I have 0 idea how to do it, so I have an OVH VPS rented, from https://www.ovhcloud.com/en-au/ and I have the web app completed, I will buy a domain, however I have no idea how to deploy react with Django, or how to separate them on deployment if needed, can anyone give me a step by step with enough resources on how to do it? -
how to set and use a foreign key for single field in Django?
from djando.db import models class server(models.Model): server_IP = models.CharField(max_length=100) Server_name = models.CharField(max_length=100) class application(models.Model): ip_address= models.ForeignKey(server_IP,on_delete=models.CASCADE) ip = models.charField(max_length=100) application_name = models.ForeignKey(ip,on_delete=models.CASCADE) application_start_date = models.DateField() = models.DateField() here i want to use ip_address as a foreign key for server_IP ip as foreignkey for application name -
How to add background image in cms
Can any one explain How to add background image in django cms Im having a html file there is background image which comes from css HTML: <div class="container"> ... </div> CSS: .container { background: url(../images/sample.jpg); background-size: cover; background-repeat: no-repeat; height: 468px; } I need to change this to placeholder to make this content editable in django cms -
How can set environment for python when there are multiple django projects on one server?
I have a server which has this structure. Nginx -> uwsgi(port:8011) DjangoA -> uwsgi(port:8012) DjangoB I developed with pipenv in local. pipenv shell pipenv manage.py runserver Now I want to put this on server with At first I try this on capistrano task :bundle do on roles(:app) do #execute "/home/ubuntu/.pyenv/shims/pip install -r #{release_path}/requirements.txt" execute "/home/ubuntu/.pyenv/shims/pipenv install" end end task :migrate do on roles(:app) do execute "/home/ubuntu/.pyenv/shims/pipenv run python #{release_path}/manage.py makemigrations" execute "/home/ubuntu/.pyenv/shims/pipenv run python #{release_path}/manage.py migrate" end end task :assets do on roles(:app) do execute "yes yes | /home/ubuntu/.pyenv/shims/pipenv run python #{release_path}/manage.py collectstatic" end end However even after pipenv installing , there is no library appears. (or it is not correctly installed??) DEBUG [50051834] Command: /home/ubuntu/.pyenv/shims/pipenv install DEBUG [50051834] Installing dependencies from Pipfile.lock (db4242)... DEBUG [50051834] π ββββββββββββββββββββββββββββββββ 0/0 β 00:00:00 DEBUG [50051834] DEBUG [50051834] To activate this project's virtualenv, run pipenv shell. Alternatively, run a command inside the virtualenv with pipenv run. INFO [50051834] Finished in 1.239 seconds with exit status 0 (successful). INFO [8a6402ea] Running /home/ubuntu/.pyenv/shims/pipenv run python /var/www/html/sokuapi/releases/20220901070724/manage.py makemigrations as ubuntu@koala.example.jp DEBUG [8a6402ea] Command: /home/ubuntu/.pyenv/shims/pipenv run python /var/www/html/sokuapi/releases/20220901070724/manage.py makemigrations DEBUG [8a6402ea] Traceback (most recent call last): File "/var/www/html/sokuapi/releases/20220901070724/manage.py", line 11, in main from django.core.management import execute_from_command_line ModuleNotFoundError: β¦ -
Django unit testing - authenticated user check in model method
I am using Django 3.2 I am trying to test a model that checks if a user is authenticated. The model code looks something like this: class Foo(Model): def do_something(user, **kwargs): if user.is_authenticated(): do_one_thing(user, **kwargs) else: do_another_thing(**kwargs) My test code looks something like this: from model_bakery import baker from django.contrib.auth import authenticate, get_user_model User = get_user_model() class FooModelTest(TestCase): def setUp(self): self.user1 = baker.make(User, username='testuser_1', password='testexample1', email='user1@example.com', is_active = True, is_superuser=False) baker.make(User, username='testuser_2', password='testexample2', email='admin@example.com', is_active = True, is_superuser=True) self.unauthorised_user = authenticate(username='testuser_2', password='wrongone') def test_user(self): self.assertTrue(self.user1.is_validated) # why is this true? - I haven't "logged in" yet? self.assertFalse(self.unauthorised.is_validated) # Barfs here since authenticate returned a None So, How am I to mock an unauthenticated user, for testing purposes? - since it appears that the is_authenticated property is read only? -
KeyError: 'slider-graph.figure'
I'm trying to render a plotly dash app to django template but I'm having error it says that 'dispatch_with_args callback_info = self.callback_map[output] KeyError: 'slider-graph.figure''. I just started using plotly-dash, I'm familiarizing it. Here's my dash app analytics = pd.DataFrame({'country': ['USA', 'UK', 'France', 'Germany', ' China', 'Pakistan', 'India'], 'users': [1970, 950, 760, 810, 2800, 1780, 2250], 'page_views': [2500, 1210, 760, 890, 3200, 1910, 2930], 'avg_duration': [75, 60, 63, 79, 57, 61, 72], 'bounce_rate': [51, 65, 77, 43, 54, 57, 51]}) # ======================== Setting the margins layout = go.Layout( margin=go.layout.Margin( l=40, # left margin r=40, # right margin b=10, # bottom margin t=35 # top margin ) ) # ======================== Plotly Graphs def get_scatter_plot(): scatterPlot = dcc.Graph(figure=go.Figure(layout=layout).add_trace(go.Scatter(x=analytics['country'], y=analytics['avg_duration'], marker=dict( color='#351e15'), mode='markers')).update_layout( title='Average Duration', plot_bgcolor='rgba(0,0,0,0)'), style={'width': '50%', 'height': '40vh', 'display': 'inline-block'}) return scatterPlot def get_pie_chart(): pieChart = dcc.Graph( figure=go.Figure(layout=layout).add_trace(go.Pie( labels=analytics['country'], values=analytics['bounce_rate'], marker=dict(colors=['#120303', '#300f0f', '#381b1b', '#4f2f2f', '#573f3f', '#695a5a', '#8a7d7d'], line=dict(color='#ffffff', width=2)))).update_layout(title='Bounce Rate', plot_bgcolor='rgba(0,0,0,0)', showlegend=False), style={'width': '50%', 'height': '40vh', 'display': 'inline-block'}) return pieChart # ======================== Dash App app = DjangoDash('SimpleExample') # ======================== App Layout app.layout = html.Div([ html.H1('Website Analytics Dashboard', style={ 'text-align': 'center', 'background-color': '#ede9e8'}), get_scatter_plot(), get_pie_chart() ]) if 'SimpleExample' == '__main__': app.run_server() here is my html file {% load plotly_dash %} <div class="{% plotly_class β¦ -
Please I'm new to python and I'm trying to do a recipe app using Django. I encountered an error which is "UnboundLocalError: local variable form
this is the picture of my views.py When I ran the code I saw an this error in the browser UnboundLocalError: local variable 'form' referenced before assignment -
function has no attribute all
i am getting this attribute error (function has no attribute all) when i clicked on a question in my browser after running my server. I have gone through the code many times but couldn't find the error. View.py class IndexView(generic.ListView): template_name ='pulls/index.html' context_object_name = 'latest_question_list' def get_queryset(self): """ Return the last five published questions (not including those set to be published in the future). """ return Question.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[:5] #Detail Function class DetailView(generic.DetailView): model = Question template_name ='pulls/detail.html' def queryset(self): """ Excludes any questions that aren't published yet. """ return Question.objects.filter(pub_date__lte=timezone.now()) -
Vue - Optimal way of receiving notifications from back-end
I'm adding backend-sent notifications to my Vue 3 app. My Django backend generates notifications and saves them to the user inbox; where they can be accessed and read at any time. I'm trying to decide which way is best for the front-end to receive such notifications. Basically, I'm torn between two options: use polling; something like a setInterval of 20 seconds that simply makes a REST call to get the most recent notifications for the user open a websocket; the server pushes a message each time there's a new notification I'm leaning a little more towards the websocket option; however, I am concerned with: complexity: having to manage re-connections and all the things that can go wrong with a WS performance: I am predicting peaks of 200-300 users at a time; is having that many open WS connection a possible concern? Weighing these factors, which one would be the better choice for my needs? And how would you mitigate the drawbacks of the chosen approach? -
why i am getting the error 'temp1app.CustomUser.user_pe rmissions' or 'auth.User.user_permissions'?
Hope you are doing well, i am beginner to the django and python, encountered the error while practicing projects from the github which is the user authentication project. i have posted a code below. feel free to ask if you have any questions. i have posted a question in this StackOverflow website to find the solution for the issue. please solve the issue. Thanks a lot for your help. Traceback error: python manage.py migrate SystemCheckError: System check identified some issues: ERRORS: auth.User.groups: (fields.E304) Reverse accessor for 'auth.User.groups' clashes with reverse accessor for 'temp1app.CustomUser.groups'. HINT: Add or change a related_name argument to the definition for 'auth.User.groups' or 'temp1 app.CustomUser.groups'. auth.User.user_permissions: (fields.E304) Reverse accessor for 'auth.User.user_permissions' clashes wi th reverse accessor for 'temp1app.CustomUser.user_permissions'. HINT: Add or change a related_name argument to the definition for 'auth.User.user_permissions' or 'temp1app.CustomUser.user_permissions'. temp1app.CustomUser.groups: (fields.E304) Reverse accessor for 'temp1app.CustomUser.groups' clashes wi th reverse accessor for 'auth.User.groups'. HINT: Add or change a related_name argument to the definition for 'temp1app.CustomUser.groups' or 'auth.User.groups'. temp1app.CustomUser.user_permissions: (fields.E304) Reverse accessor for 'temp1app.CustomUser.user_per missions' clashes with reverse accessor for 'auth.User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'temp1app.CustomUser.user_pe rmissions' or 'auth.User.user_permissions'. temp1/settings.py from pathlib import Path import os # Build paths β¦ -
in django how to link two fields of the same model with another model with the foreign key
I have a "ModelVoiture" model with a foreign key "type_carburant" field and I can access the "typeCarburant" field of the "Carburant" model. I need to access another field of the same model "Carburant", the field "prixCarburant" from the model "ModelVoiture" but if I add the line prixCarburant = models.ForeignKey(Carburant, on_delete=models.CASCADE) i have this error coutcarbur.ModelVoiture.prixCarburant: (fields.E304) Reverse accessor 'Carburant.modelvoiture_set' for 'coutcarbur.ModelVoiture.prixCarburant' clashes with reverse accessor for 'coutcarbur.ModelVoiture.typeCarburant'. HINT: Add or change a related_name argument to the definition for 'coutcarbur.ModelVoiture.prixCarburant' or 'coutcarbur.ModelVoiture.typeCarburant'. coutcarbur.ModelVoiture.typeCarburant: (fields.E304) Reverse accessor 'Carburant.modelvoiture_set' for 'coutcarbur.ModelVoiture.typeCarburant' clashes with reverse accessor for 'coutcarbur.ModelVoiture.prixCarburant'. HINT: Add or change a related_name argument to the definition for 'coutcarbur.ModelVoiture.typeCarburant' or 'coutcarbur.ModelVoiture.prixCarburant'. my code in coutcarbur/models.py class MarqueVoiture(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Carburant(models.Model): name = models.CharField(max_length=50) prixCarburant = models.DecimalField(max_digits=6, decimal_places=2) typeCarburant = models.CharField(max_length=50) def __str__(self): return self.name class ModelVoiture(models.Model): name = models.CharField(max_length=50) consolitre = models.DecimalField( max_digits=6, decimal_places=2) prixCarburant = models.ForeignKey(Carburant, on_delete=models.CASCADE) typeCarburant = models.ForeignKey(Carburant, on_delete=models.CASCADE) marque = models.ForeignKey(MarqueVoiture, on_delete=models.CASCADE) def __str__(self): return self.name how to implement related_name function in template to solve this problem. I must surely revise the diagram of my models? thanks for any help. -
Item update query produced by django is wrong
I am trying to update one item at a time using the Django ORM with TimescaleDB as my database. I have a timesacle hypertable defined by the following model: class RecordTimeSeries(models.Model): # NOTE: We have removed the primary key (unique constraint) manually, since we don't want an id column timestamp = models.DateTimeField(primary_key=True) location = PointField(srid=settings.SRID, null=True) station = models.ForeignKey(Station, on_delete=models.CASCADE) # This is a ForeignKey and not an OneToOneField because of [this](https://stackoverflow.com/questions/61205063/error-cannot-create-a-unique-index-without-the-column-date-time-used-in-part) record = models.ForeignKey(Record, null=True, on_delete=models.CASCADE) temperature_celsius = models.FloatField(null=True) class Meta: unique_together = ( "timestamp", "station", "record", ) When I update the item using save(): record_time_series = models.RecordTimeSeries.objects.get( record=record, timestamp=record.timestamp, station=record.station, ) record_time_series.location=record.location record_time_series.temperature_celsius=temperature_celsius record_time_series.save() I get the following error: psycopg2.errors.UniqueViolation: duplicate key value violates unique constraint "5_69_db_recordtimeseries_timestamp_station_id_rec_0c66b9ab_uniq" DETAIL: Key ("timestamp", station_id, record_id)=(2022-05-25 09:15:00+00, 2, 2) already exists. and I see that the query that django used is the following: {'sql': 'UPDATE "db_recordtimeseries" SET "location" = NULL, "station_id" = 2, "record_id" = 2, "temperature_celsius" = 26.0 WHERE "db_recordtimeseries"."timestamp" = \'2022-05-25T09:15:00\'::timestamp', 'time': '0.007'} On the other hand the update is successful with update(): record_time_series = models.RecordTimeSeries.objects.filter( record=record, timestamp=record.timestamp, station=record.station, ) record_time_series.update( location=record.location, temperature_celsius=temperature_celsius, ) and the sql used by django is: {'sql': 'UPDATE "db_recordtimeseries" SET "location" = NULL, "temperature_celsius" = β¦ -
Django Channels: How can I run WSGI inside a Channels app?
I am going to write a Django chat apps using Channels. I haven't started yet, but I just want to know this: How can I run existing WSGI apps using Channels, which uses ASGI? I have Django 4.1 installed and Python 3.8 (i haven't installed Channels yet but i will) Thanks in advance :) -
return response number of count in django rest framework
I wanted to return the response number of the count of chiled_comments as in blew table. like for id no. 3 have 2(count) "parent_post_comment_id". and same as id no. 1 have only 1(count) "parent_post_comment_id". id is_post_comment parent_post_comment_id created_on description language_post_id 1 1 2022-08-30 09:06:07.078366 Comment Create 001!!! 2 2 1 2022-08-30 09:11:23.255055 Comment Create 002!!! 2 3 1 2022-08-30 09:16:45.394074 Comment Create 003!!! 2 4 0 3 (child of comment 3) 2022-08-30 12:26:48.076494 Comment Create 003-1!!! 2 5 0 3 (child of comment 3) 2022-08-30 12:27:10.384464 Comment Create 003-2!!! 2 6 0 2 (child of comment 2) 2022-08-30 12:27:27.306202 Comment Create 002-1!!! 2 7 0 2 (child of comment 2) 2022-08-30 12:27:37.405487 Comment Create 002-2!!! 2 8 0 1 (child of comment 1) 2022-08-30 12:27:53.771812 Comment Create 001-1!!! 2 models.py class Comments(models.Model): language_post = models.ForeignKey(PostInLanguages, null=False, related_name='comment_data', on_delete=models.CASCADE) is_post_comment = models.BooleanField(default=True) parent_post_comment_id = models.PositiveIntegerField(null=True) user = models.ForeignKey(User, on_delete=models.CASCADE) description = models.CharField(max_length=400, blank=False) created_on = models.DateTimeField(default=timezone.now) views.py class CommentGetView(viewsets.ViewSet): def retrieve(self, request, post_id=None, post_language_id=None, *args, **kwargs): try: post_in_lang = PostInLanguages.objects.get(id=post_language_id) post_in_lang_id = post_in_lang.id except PostInLanguages.DoesNotExist as e: return Response({"response": False, "return_code": "languages_post_not_exist", "result": "Comment_Get_Failed", "message": errors["postinlanguages_DoesNotExist"]}, status=status.HTTP_400_BAD_REQUEST) try: queryset = Comments.objects.filter(language_post_id=post_in_lang_id,is_post_comment=True) except Comments.DoesNotExist as e: return Response({"response": False, "return_code": "comments_not_exist", "result": β¦ -
How to add header parameter to all url paths in drf_spectacular?
I'm using drf_spectacular to be able to use swagger and it's working fine. I define the required parameters for my API views (whether in the path or in the header) like this: @extend_schema( OpenApiParameter( name='accept-language', type=str, location=OpenApiParameter.HEADER, description="fa or en. The default value is en" ), ) but I don't want to add these lines of code to all of my API views. Is there an easy way to do this? (Something like defining these lines of code in SPECTACULAR_SETTINGS) I already found an APPEND_COMPONENTS option in drf_spectacular's documentation but I'm not familiar with it. -
Django Rest Framework admin styling messed up
I recently noticed my Django admin styling is messed up. The CSS seems to be working though and everything works, but once you click on a model, the next page is messed up. Does anyone know what causes this? I don't remember changing anything that would cause this. -
.Please try to help me. TypeError: UserManager.create_superuser() missing 1 required positional argument: 'username'
When I established a connection with MYSQL for the existing django data and trying to create a super user, above issue is raising. I cleared the db.sqlite3 database and it's migrations also models.py: from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): name = models.CharField(max_length=20, null=True) email = models.EmailField(unique=True, null=True) bio = models.TextField(max_length=200, null=True) avatar = models.ImageField(null=True, default="avatar.svg") USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] forms.py: from django.forms import ModelForm from django.contrib.auth.forms import UserCreationForm from .models import Room, User class MyUserCreationForm(UserCreationForm): class Meta: model=User fields= ['name', 'username', 'email', 'password1', 'password2'] class UserForm(ModelForm): class Meta: model=User # assigning 'User' table or class from the models(db) fields = ['avatar', 'name', 'username', 'email', 'bio'] views.py: def loginPage(request): page = 'login' if request.user.is_authenticated: return redirect('home') if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') try: user = User.objects.get(username=username) except: messages.error(request, 'Incorrect Username') user=authenticate(request, username=username, password=password) #If cond to check the correct user or not if user is not None: login(request, user) return redirect('home') else: messages.error(request, 'Incorrect Username or password') context={'page':page} return render(request, 'base/login_register.html', context) def logoutUser(request): logout(request) return redirect('home') def registerPage(request): page = 'register' form = MyUserCreationForm() if request.method == 'POST': form = MyUserCreationForm(request.POST) if form.is_valid(): #commit is to get the instance from β¦ -
Django pipedream through's exception: module 'pipedream' has no attribute 'steps'
I am using Twilio to send SMS in my Django application. and getting that message status from pipedream, but getting this error module 'pipedream' has no attribute 'steps'. In the pipedream website with this code, I get status but in my project, I am getting an error. Here is my code for a pipedream. status = pipedream.steps["trigger"]["event"]["body"]["SmsStatus"] I am attaching the screenshot of the pipedream. -
Django filter on Datetmefield
I have a model like below: class example(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=64) start_time = models.DateTimeField() end_time = models.DateTimeField() And I have below query: ohlcv_data = example.objects.filter( name='John', start_time__gte=datetime.datetime.strptime('2022-07-26 2019:30:00','%Y-%m-%d %H:%M:%S') end_time__lte=datetime.datetime.strptime('2022-07-26 2019:35:00','%Y-%m-%d %H:%M:%S')) For each minute i have a record so for top example i should give five record, but nothing returend. -
Include tag Django: Pass template name as variable from AJAX response
This is the template code in Django, where "condition_template.html" should be replaced with template name variable {% include "condition_template.html" %} I want to pass the condition_template_name which returned from AJAX API call response below: $.ajax({ url: get_template_data_url, type: "GET", dataType: 'json', success: function (data) { var condition_template_name = data['condition_template_name'] } }); -
My Django site is not accessible on HTTPS using AWS
Hope you are doing well.I have Deployed my Django website on AWS Ec2 instanace using Windows Virtual machine.I had pasted my all code in RDP and then started server on port 80 like below: python manage.py runserver 0.0.0.0:80 and then i opened my IPV4 and DNS in browser.My site works as expected.After that i tried to install SSL Certificate for my site and this issued successfully.I also setup load balancer for it.Everything i had setup for it as mentioned in blog.But my site is not accessible on https://fableey.com but it opens when i write this url http://fableey.com.I just need to solve my problem. I already added all security groups rules to allow http & https.But where is the problem.I think as my django server is running on port 80 therefore it allows http only ,but how i can run my django server on 443 ,so that my site is accessible through https like this https:/fableey.com Thanks for your help !!! -
I'm new to Django, I've created very simple Django App that takes JSON and shares link for output CSV's folder
views.py enter image description here def downloadfile(request): base_dir = os.path.dirname(os.path.dirname(__file__)) filepath = base_dir + '\media\output_csv' response = StreamingHttpResponse(filepath) response['Content-Length'] = os.path.getsize(filepath) response['Content-Disposition'] = "Attachment;filename=%s"%filename return response It is starting a download but nothing is getting downloaded. If there is a better method let me know. -
how to use image and embeded link as option in django model form
I am trying to create a form in which I want the user to give some option as an image and the user has to choose in b/w them but I have no idea how to do it I place an image in HTML t shows the user the image but I want to save that image option in my database also here is my code class Personal_readme(models.Model): system_choice = [ ('windows', 'windows'), ('linux', 'linux'), ('macOs', 'macOs'), ('unix', 'unix') ] work_status_Regex = RegexValidator(regex = "((http|https)://)(www.)?[a-zA-Z0-9@:%._\\+~#?&//=]{2,256}\\.[a-z]{2,6}\\b([-a-zA-Z0-9@:%._\\+~#?&//=]*)") name = models.CharField(max_length=70, blank=False) about_me = models.CharField(max_length=100, blank=True) work_status = models.CharField(max_length=70, blank=True) work_status_link = models.URLField(validators = [work_status_Regex], blank=True) system = MultiSelectField(max_length=20, choices=system_choice,max_choices=4, blank=True ) def __str__(self): return self.name as you can see I want to give the user a system choice on which they like to work on but instead of the name I want to give image option and also if a user clicks on that image it throws him to the external link about that image or that organization official website Any idea will helpful -
Django Migratons: What is the best default way to dump and load data in DB apart from using third party app?
I'm new to Django and interested in knowing in-depth about migrations so I don't want to use the third-party apps(ex. flyway..) I want to know how to dump hundreds of data in my Postgres DB without using 3rd party applications. -
Django query to filter date range
I have a model which contains date range i want to filter the data based on the range date that is i want the data who's date range is 90 days from today's date. class MyModel(models.Model): name = models.CharField(max_length=255) start_end_date = ranges.DateTimeRangeField(validators= [validate_range_date_time]) so when we select the start date on page the end date will popoulate the same date but i cannot concatenate filter just by today date + timedelta(days=90) this is one single date and the field is date range, so how can i filter the date range data which is 90 days from now. the model stores start_end_date as 'start_end_date': DateTimeTZRange(datetime.datetime(2022, 11, 29, 9, 15), datetime.datetime(2022, 11, 29, 10, 0), Mymodel.objects.filter(start_end_date__contains=timezone.now() + timezone.timedelta(days=90)) timezone.now() + timezone.timedelta(days=90) = datetime.datetime(2022, 11, 29, 22, 52, 7, 759648) the query is giving empty set