Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Print all values for Single object in Django?
i am selecting last object from my table using following Code data= MyModel.objects.last() This is Displaying object. i want to display full array of 'data' object.for that i am using Following Code data= MyModel.objects.last().values() However its not Working.How to do that? -
Emulating linux command line in python django web app
I was looking for technology to create GUI(in C++ or Python) to C command-line app. I've found some desktop libraries(e.g. Tkinter), but I was not satisfied with them, so I thought that I could use Python Django and Angular to create a pretty web app that will serve as my GUI. And here is a problem as I am new to this technology is there any way to emulate Linux shell using django in the web app. For me this is crucial for debugging the application. -
Django Dynamics URL No Reverse Match at /
I am trying to create a dynamic url but keep getting the same error. What have I done wrong here, to cause this issue? I am trying to use the default id field. Error Message NoReverseMatch at / Reverse for 'update_ticket' with arguments '('',)' not found. 1 pattern(s) tried: ['update_ticket/(?P<pk>[^/]+)/$'] views.py def updateTicket(request, pk): ticket = Ticket.objects.get(id=pk) form = TicketForm(instance=ticket) if request.method == 'POST': form = TicketForm(request.POST, instance=ticket) if form.is_valid(): form.save() return redirect('/') context = {'form':form} return render(request, 'itdb/ticket_form.html', context) urls.py path('update_ticket/<str:pk>/', views.updateTicket, name="update_ticket"), -
How to implement a people availability api in DRF?
python: 3.7 django 3 I am trying to build an API using DRF to arrange a meeting between people base on each person. One person can have many availability dates while availability date can be share for many persons. I have the following schema: from django.db import models # models.py class Availability(models.Model): date = models.DateField() start = models.TimeField() end = models.TimeField() class Meta: unique_together = ('date', 'start', 'end') class Person(models.Model): email = models.EmailField(max_length=70, primary_key = True) date = models.DateField() start = models.TimeField() end = models.TimeField() availability = models.ManyToManyField(Availability) My wish is that after a person insert his Availability I would like to iterate over the time and insert it to the Availability model as hourly Availability Exmaple: A person Availability could be the following (19.09.2022, 09:00 - 12:00) I would like to do the following: iterate over the person time and save each Hour in the Availability table, meaning insert (19.09.2022, 09:00, 10:00), (19.09.2022, 10:00, 11:00), (19.09.2022, 11:00, 12:00) for each insert save in the Person field with the availability id which was created I am not sure how to implement the logic,I thought about the following: should I in the serializers.py in the Person create function iterate and insert … -
Python Django: Process DataFrame and perform calculations to use in chart.js
I'm trying to get my head around dataframes. I'm trying to get a key-value list with as key the date and as value the total SUM price of all the provided stocks on that day. I was reading on dataframes and noticed that some people mentioned that using iterrows() is not advised and that you should do you calculations within the dataframe. But I'm failing to see how I should do that and have a list that I can pass through to my chart.js data. Code data = yf.download( # or pdr.get_data_yahoo(... # tickers list or string as well tickers = "AAPL GOOGL NIO"), # use "period" instead of start/end # valid periods: 1d,5d,1mo,3mo,6mo,1y,2y,5y,10y,ytd,max # (optional, default is '1mo') period = "ytd", # fetch data by interval (including intraday if period < 60 days) # valid intervals: 1m,2m,5m,15m,30m,60m,90m,1h,1d,5d,1wk,1mo,3mo # (optional, default is '1d') interval = "1d", # group by ticker (to access via data['SPY']) # (optional, default is 'column') group_by = 'ticker', # adjust all OHLC automatically # (optional, default is False) auto_adjust = False, # download pre/post regular market hours data # (optional, default is False) prepost = False, # use threads for mass downloading? (True/False/Integer) # (optional, default … -
what is the best way to learn Django 3 (Django learning path)
i am a full stack developer and i use "node.js" but i wanna learn django i don't how i start i searched on udemy and all course start full stack from scratch and i tried to learn from the official website but i couldn't, i need to know what should i learn with django what the database is most used i am good with python -
TypeError: got an unexpected keyword argument 'entry'
I am in the middle of creating an encyclopedia project. On the home page is a list of entries and I want all the entries to be linked to their entry page. Currently when I click on the link to an entry on the homepage, in this case the entry is called CSS, this is the error I get: TypeError at /wiki/CSS/ entry() got an unexpected keyword argument 'entry' Request Method: GET Request URL: http://127.0.0.1:8000/wiki/CSS/ views.py def css(request): return render(request, "entries/css.html", { "css_entry": util.get_entry("css") }) def entry(request): return render(request, entry, "encyclopedia/index.html", { "entry": util.get_entry({"entry"}) }) urls.py urlpatterns = [ path("", views.index, name="index"), path("css/", views.css, name="css"), path("<str:entry>/", views.entry, name="entry") ] index.html <ul> {% for entry in entries %} <li><a href = "{% url 'entry' entry %}">{{ entry }}</a></li> {% endfor %} </ul> The frustrating thing is if I enter into the browser: http://127.0.0.1:8000/wiki/CSS/ it works and the page loads fine but not when I click the link from the homepage. Plus, if I remove the entry argument leaving it as {% url 'entry' %} then the homepage stops working and I get the following error: NoReverseMatch at /wiki/ Reverse for 'CSS' not found. 'CSS' is not a valid view function or … -
Django: ManyToManyField with intermediary model error
Django is not managing our databases for us, therefor I created the table RulesetRuleMap to handle the ManyToMany relationship between Ruleset and Rule: Each Ruleset can consist of multiple Rules and each Rule can be used in multiple Rulesets. Models class Rule(models.Model): id = models.BigAutoField(primary_key=True) percentage_of_total = models.FloatField(blank=False, null=False) _rule_parameter = models.ForeignKey('RuleParameter', models.DO_NOTHING, blank=False, null=False) class Meta: managed = False db_table = '_rule' class Ruleset(models.Model): id = models.BigAutoField(primary_key=True) name = models.CharField(max_length=300, blank=False, null=False) description = models.CharField(max_length=300, blank=False, null=False) rules = models.ManyToManyField('Rule', through="RulesetRuleMap") class Meta: managed = False db_table = '_ruleset' class RulesetRuleMap(models.Model): id = models.BigAutoField(primary_key=True) _rule = models.ForeignKey('Rule', models.CASCADE) _ruleset = models.ForeignKey('Ruleset', models.CASCADE) class Meta: managed = False db_table = '_ruleset_rule_map' Serializers class RulesetRuleMapSerializer(serializers.ModelSerializer): class Meta: model = db_models.RulesetRuleMap fields = '__all__' class RuleSerializer(serializers.ModelSerializer): class Meta: model = db_models.Rule fields = '__all__' class RulesetSerializer(serializers.ModelSerializer): rules = RuleSerializer(many=True) class Meta: model = db_models.Ruleset fields = '__all__' def create(self, validated_data): rules_data = validated_data.pop('rules') ruleset = db_models.Ruleset.objects.create(**validated_data) rules_storage =[] for rule_data in rules_data: rule, created = db_models.Rule.objects.get_or_create(**rule_data) rules_storage.append(rule) ruleset.rules.add(*rules_storage, through_defaults={}) return ruleset On a homepage the user can add/modify a Ruleset and add/modify the assosiated Rules. On submission we receive a payload like this: { "id": None, "name": "Split_50.0_Param1_50.0_Param2", "description": "test", "rules": [ … -
The best way to divide card-deck into rows in django template - django
i want to show 6 item in page in same design , like this photo https://pasteboard.co/Jrkehgg.png i have this code in html page : {% for android in single_android_post %} <div class="card-deck"> <div class="card"> <img class="card-img-top" src="{{ android.get_image }}" height="240px" width="230px" alt="اذا رأيت هذه الجمله فيرجى التواصل معنا واخبارنا بمكان الخطا لاصلاحه"> <div class="card-body"> <h5 class="card-title">{{ android.name }}</h5> <p class="card-text"> {{ android.app_contect}} </p> </div> <div class="card-footer"> <small class="text-muted">{{ android.post_date}}</small> <small class="firstsmall"><a class="bg-orange" href="" title="">{{ android.post_tag}}</a></small> </div> </div> </div> {% endfor %} i tried this code but each card take all page in width ,,, how to fix it ? -
Django: No such table while rewriting the "User" class
I'm making a Django project with Django 3.1. I was trying to rewrite the User class in Django. This is what I wrote in app_questions/models.py: import django.contrib.auth.models from django.contrib.auth.models import AbstractUser class User(AbstractUser): #pass settings.py: AUTH_USER_MODEL = 'app_questions.User' Also I created an superuser before I did these all. After that I did makemigrations and migrate in the cmd and ran the server. I open the admin page and try to edit the User I created beforehand, but when I click the edit page, this error occured: OperationalError at /admin/app_questions/user/1/change/ no such table: app_questions_user_groups Request Method: GET Request URL: http://127.0.0.1:8000/admin/app_questions/user/1/change/ Django Version: 3.1 Exception Type: OperationalError Exception Value: no such table: app_questions_user_groups Exception Location: C:\Users\*\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\sqlite3\base.py, line 413, in execute Python Executable: C:\Users\*\AppData\Local\Programs\Python\Python37-32\python.exe Python Version: 3.7.4 Python Path: ['C:\\Users\\*\\django_sample\\vitural_env\\zeaf', 'C:\\Users\\*\\AppData\\Local\\Programs\\Python\\Python37-32\\python37.zip', 'C:\\Users\\*\\AppData\\Local\\Programs\\Python\\Python37-32\\DLLs', 'C:\\Users\\*\\AppData\\Local\\Programs\\Python\\Python37-32\\lib', 'C:\\Users\\*\\AppData\\Local\\Programs\\Python\\Python37-32', 'C:\\Users\\*\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages'] I found a few posts to solve this. These are methods I tried: makemigrations and migrate (same error) migrate (appname) --fake (same error) Add things into the User class (error in /admin: no such column) migrate --sync-db (same error) migrate --run-syncdb (same error) $ manage.py (appname) zero (failed: Unknown command) migrate --fake (appname) zero (same error) They all didn't solve the problem. Posts in 2016 or 2017 seems … -
HyperlinkedRelatedField Nesting Hyperlinks - object has no attribute
I have two models: Parent and Child. Child has a ForeignKey field in the model, which points to the Parent Model. I am trying to add a HyperlinkedRelatedField to the Parent serializer, which should create a list of all hyperlinks in a single item, which point to the Child instances, that have parent_id in them. In other words, what I want to get: [ { "id": 1, "name": "Parent 1", "children": [ "http://localhost:8000/child/1/", "http://localhost:8000/child/2/" ] }, { "id": 2, "name": "Parent 2", "children": [ "http://localhost:8000/child/3/" ] }, ... ] However, when I add the code, I receive the error: 'Parent' object has no attribute 'childen' I tried to read the REST DOCUMENTATION (particularly HyperlinkedRelatedField), tried to change the moles such as shown in the example by adding the related_name field, but it doesn't work for me. More specifically, it just doesn't want to see or connect to the child. Also, I tried to change the attributes in the HyperlinkedRelatedField to make it work, but it always gives me the error that is stated up-top. I have been trying to Google the problem, which gave me some of the results, but they don't apply to me or I just don't understand … -
Django - if value add 3 and update to IntegerField
I'm making a score app. Users can guess the next game result / winner. Now if the user guess the winning team, I want the userscore (points) to add 3 to the DB field. For this I got following Models: class Customer(models.Model): name = models.ForeignKey(User, on_delete=models.CASCADE) points = models.IntegerField(null=True, default=0) class Tipp(models.Model): user = models.ForeignKey(Customer, on_delete=models.CASCADE, null=True, blank=True) result_hometeam1 = models.IntegerField(null=True, blank=True) result_guestteam1 = models.IntegerField(null=True, blank=True) class Game(models.Model): hometeam1 = models.ForeignKey(Teams, on_delete=models.CASCADE, related_name="hometeam1", blank=True, null=True) result_hometeam1 = models.IntegerField(null=True, blank=True) guestteam1 = models.ForeignKey(Teams, on_delete=models.CASCADE, related_name="guestteam1", blank=True, null=True) result_guestteam1 = models.IntegerField(null=True, blank=True) E.G the user guess results: hometeam1 vs. guestteam1 10:20 and the final result is 15:20 the user guess the right winner and the points row should get 3 points to the current value. I tried to do in the template but thats not a good choice: {% if game.get.result_hometeam1 <= user_tipp.get.result_hometeam1 %} {{ users.get.points|add:3 }} {% endif %} I havn't found a method to do this if statement in the views.py. I searched for Query Expressions in the Docs but I couldn't found a solution. -
while trying to signin using postaman it throws as error of csrf token
when I try to login using a browser it works correctly but, when I try to user Postman to post username & password it throws csrf token error. urlpatterns = [ path('', include('rest_framework.urls')), ....... ] Middlewares MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', ] When I access the api from a browser is allows me to log in. Currently not using any Permission classes and authentication_classes. but tested with rest_framework_simplejwt.authentication.JWTAuthentication at the begining. Currently not using any. -
How can I access attributes of a model in admin.TabularInline that is at the end of a manytomany relationship with defined through model
I am facing the following scenario; #models.py class A(models.Model): dog = models.CharField(...) cat_values = models.ManyToManyField(B, through='AtoB') class AtoB(models.Model): one = models.ForeignKey(A) two = models.ForeignKey(B) class B(models.Model): cat = models.CharField(...) #admin.py class BForm(forms.ModelForm): cat = forms.TextInput() class Meta: model = A.cat_values.through exclude = [] class BInline(admin.TabularInline): model = B.cat_values.through form = BForm fields = ['cat', ] readonly_fields = ['cat', ] @admin.register(A) class AAdmin(admin.ModelAdmin): inlines = [BInline,] When I try to run server, I get the following error message; <class 'agregator.admin.AAdmin.BInline'>: (admin.E035) The value of 'readonly_fields[0]' is not a callable, an attribute of 'BInline', or an attribute of 'agregator.AtoB'. No other forms of access really work like A.cat_values or A.cat_values.two I partially understand where is the problem coming from. It does not let me access the B's attributes, only AtoB's attributes. I have tried to work around it but unsuccessfully. Have read the documentation but there is nothing about accessing the attributes in this case scenario, only without a defined through model. eg https://docs.djangoproject.com/en/3.1/topics/db/examples/many_to_many/ or https://docs.djangoproject.com/en/3.1/topics/db/models/ I need to display the cat attribute in the inline in the A's admin. Any help would be much appreciated. -
Django - Updating forms when chagning login from username, to email
I have changed my django project, to use email addresses instead of passwords when logging in. To do this, i create a custom user model as so: class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_user(self, email, password, **extra_fields): """ Create and save a User with the given email and password. """ if not email: raise ValueError(_('The Email must be set')) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user and class CustomUser(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email Now in my views, im using django's built in views for the user account lifecycle, path('accounts/', include("django.contrib.auth.urls")). But now, my register and login forms are incorrect. They ask for usernames, not email. (interestingly, the login form with username still works, not really sure why). My question is, how do I update these forms to reflect email addresses, and not username? Thanks, -
Why can't I create an instance of a class inside an abstract class
I am using django-parler for language translation in an abstract class model but I get this error: raise TypeError("Can't create TranslatedFieldsModel for abstract class {0}".format(shared_model.__name__)) TypeError: Can't create TranslatedFieldsModel for abstract class MyClass I want to know why I can't create an instance of this TranslatedFieldsModel in an abstract class. Are there some instance or some type of classes/objects that cannot be instantiated in an abstract class? I really don't know much about abstract classes, please explain to me why this TranslatedFieldsModel cannot be created and how to go about it -
How to check request.FILES is black or not in Djnago?
I am using Djnago.i Have html Form such as below, <form method="POST" action="{% url 'someaction' %}" enctype="multipart/form-data"> <input type="file" name="image" id="image"> </form> How to check request.FILES['image'] is Selected or not in djnago view file? -
Django don't refrash page and menu in during work in admin-side
We met very strange behavior of DjangoCMS. Desctiption of problem After adding any page, sotimes it disappear, sometimes appear. Refrash page througth CTRL+F5 item of menu also sometimes appear and disappear. What is problem? Example on video: https://yadi.sk/i/366VZBjy7xrChg We are using Nginx 1.19.0, Django CMS 3.7.1 на Django 2.2 and Postgres 12.3 Thanks a lot for any help! -
Django (GET) - Is it posible to pass multiple values in only one parameter, instead of multiple parameters called the same
I'm developing an web app with Django to query and download data from multiple weather stations. It's almost everything good but something that I don't like it's that when I filter by stations, the form passes them to the URL like this: https://my-server/stations?station_name=1&station_name=2&station_name=3 And since the number of selected stations can reach more than 250 (this added to the fact that spatial data are also passed in the URL as coordinates, polygons...), I would like to know if there is any way to obtain the "station_name" parameter in a list format like this or similar, for me to later divide it in my views.py: https://my-server/stations?station_name=1%3B2%3B3 On the other hand, I'm not sure if there are any contraindications when generating too long URLs, if not I have no problem maintaining the current format, but otherwise I would like to find a solution. Thanks in advance -
How to get object by name in views.py django
How to get object in views.py using name not by id. def StockSummaryPage(request, title): stocks_data = get_object_or_404(Stock, string=title) return render(request, 'stocks/stock_summary_page.html', {'stocks_data':stocks_data}) This is my views.py and in stocks_data = get_object_or_404(Stock, string=title) we use pk= stock_id but i want to do it by title. So help me -
Cant send a message to a Django channel
I want to send a message over a channel using Django Channels. This is how I'm doing. I create a consumer first. I'm able to echo back the received messages. However, not able to send messages to a specific channel/group. class Consumer(AsyncJsonWebsocketConsumer): """Consumer.""" def _get_connection_id(self): return ''.join(e for e in self.channel_name if e.isalnum()) async def connect(self): scope = self.scope user_id = str(scope['user'].user_id) connection_id = self._get_connection_id() # Adding connection to DB. obj = UserConnection.add(connection_id=connection_id, user_id=user_id) # Accept the connection await self.accept() # Adding current to group. await self.channel_layer.group_add( user_id, connection_id, ) async def disconnect(self, close_code): """Remove the connection and decrement connection_count in DB.""" connection_id = self._get_connection_id() user_id = str(self.scope['user'].user_id) UserConnection.drop(connection_id=connection_id) # Dropping from group. await self.channel_layer.group_discard( user_id, connection_id, ) async def receive_json(self, data, **kwargs): """Receive messages over socket.""" resp = data # I'm able to echo back the received message after some processing. await self.send(json.dumps(resp, default=str)) # This does not works. def send_to_connection(connection_id, data): """Send the data to the connected socket id.""" return get_channel_layer().group_send(connection_id, data) Now when I try to send a message, the connected socket does not receives the message. >>> connection_id = UserConnection.objects.get(user_id=user_id).connection_id >>> send_to_connection(connection_id, {'a':1}) # returns <coroutine object RedisChannelLayer.group_send at 0x109576d40> What's the issue in the code? -
How to override post method of generics.ListCreateAPIView?
guys. I'm writing backend for application that allow voting for best pizza. I have Pizza model (id, name, price), built-in User model, Vote model(id, author [models.ForeignKey], pizza[models.ForeignKey]). In my project I implement view class VoteList(generics.ListCreateAPIView): queryset = Vote.objects.all() serializer_class = VoteSerializer And now I want to implement check if authenticated user posts vote with his id. If it is True, I want to save it into the datebase, else I don't want to save it and return HTTP with error if request.user.pk == self.serializer_class.Meta.model.author: So could you, please, help me to implement this functionality -
Wagtail not indexing body field
I'm trying to search. It can find words from the 'title' but not from the 'body' text. I have no further settings only defaults. Any ideas? class StandardPage(Page): body = RichTextField(features=['h2', 'bold', 'italic', 'link', 'ol', 'ul', 'document-link', 'image', 'embed']) sidebar_image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) # Search index configuration search_fields = Page.search_fields + [ # Inherit search_fields from Page index.SearchField('body'), ] and this is my view.py def search(request): search_query = request.GET.get('query', None) page = request.GET.get('page', 1) # Search if search_query: search_results = Page.objects.live().search(search_query) query = Query.get(search_query) # Record hit query.add_hit() else: search_results = Page.objects.none() return render(request, 'search/search.html', { 'search_query': search_query, 'search_results': search_results, }) -
elasticsearch.exceptions.ConnectionError: Failed to establish a new connection:
When I run python src/manage.py search_index --rebuild -f I get the following error elasticsearch.exceptions.ConnectionError: ConnectionError(<urllib3.connection.HTTPConnection object at 0x7f4bd08259e8>: Failed to establish a new connection: [Errno -2] Name or service not known) caused by: NewConnectionError(<urllib3.connection.HTTPConnection object at 0x7f4bd08259e8>: Failed to establish a new connection: [Errno -2] Name or service not known) I am not familiar with elastic search. in my settings/base.py, I have ELASTICSEARCH_DSL={ 'default': { 'hosts': '127.0.0.1:9260' }, } and my docker-compose.yml elastic: image: docker.elastic.co/elasticsearch/elasticsearch:7.5.1 ports: - 9260:9200 environment: http.host: 0.0.0.0 transport.host: 127.0.0.1 volumes: - ./config/elastic/elasticsearch.yml:/usr/share/elasticsearch/config/elasticsearch.yml - elasticsearch:/usr/share/elasticsearch/data Please let me know if any other information needed. Thank you in advance -
'NoneType' object has no attribute '_prefetch_related_lookups' in Django Form
I am having a form and I am using chained dropdown in it .... I'm following this tutorial and created two htmls for showing the dropdown and appending it with Ajax call https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html but I am unable to edit it .... It showing an error like this " 'NoneType' object has no attribute '_prefetch_related_lookups'" class PlaceLoadForm(forms.Form): state = forms.ModelChoiceField(queryset=None, required=True) city = forms.ModelChoiceField(queryset=None, required=True) def __init__(self, query=None, city=None, * args, **kwargs): super().__init__(*args, **kwargs) if query: try: self.fields['city'].queryset = City.objects.filter( id=query) except (ValueError, TypeError): pass if query and city: if project: self.fields['state'].initial = query if task: self.fields['city'].initial = city in my views.py def create_time_entry(request, list_id=None): form = DetailEntry(request.POST or None, instance=query, user=request.user or None) module_from = ProjectLoadForm() if request.method == 'GET': if query: city = City.objects.filter(id=query.city) data['form'] = form data['placeload_form'] = PlaceLoadForm(query, city) data['query'] = query return render(request, 'time_sheet/NewFormTimeSheet.html', data) In my html When I am calling like this {{ placeload_form.city|add_class:'form-control full-width' }} It throwing one error 'NoneType' object has no attribute '_prefetch_related_lookups'