Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to upgrade SQLite 3.7 to SQLite 3.8 in Linux CentOS ,python version 3.6 and django version is 3
When I am running command python3 mange.py runserver I am getting error improperly configured SQLite 3.8.3 found 3.7 . Django version is 3. I also checked similar problems on stackoverflow but in my case it doesn't work -
how can i get data manytomay relation from 3 tables django
class Product(models.Model): name = models.CharField(max_length=30) class Order(models.Model): order_number = models.CharField(max_length=30) products = models.ManyToManyField( Product, through='OrderProduct', related_name='orders' ) class OrderProduct(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) price = models.CharField(max_length=30) quantity = models.IntegerField(null = True) product = models.ForeignKey(Product, on_delete=models.CASCADE) my data is already save in these Models now when i fetch order then i want to see Order product data also how can i see these data ? again 1 order has multi order products i try this abc = Order.object.get(id = 1) now how can i see the related products and its quantity and price? -
Implementing a hierarchical system in django using django treebeard
I am trying to implement a web based organisational church system which has a hierarchy as shown in the diagram. I want to implement the system using django treebeard materialized path . I want each node on the tree to be an instance of a Church where a single church in the tree can manage its content also the Admin and the users can be able to login to the Church they belong to. I also need the parent node to be able to access the some data of the child nodes. Is this possible? If you have any idea or leads, please help. Thanks in advance. here is a diagram of the tree -
Use Django to create tables dynamically
I am a beginner in Django, I wish to know if the following is possible in Django. I will have a folder called 'data' into which say I store 2 csv files 'FileA' and 'FileB'. The contents of these are not defined in any model in my Django app. I wish to read the csv files, get the header information from each and dynamically create Tables/Models using this information and load the csv data into these tables. So, for example, if FileA has 3 columns, ColA,ColB,ColC, then I wish to create a model/table named 'FileA', with 3 fields 'ColA','ColB' and 'ColC' and insert the csv data into these tables. Is this possible with Django, or do I have to create,register,migrate to do this manually each time? Any references would be appreciated. Thanks. -
How to add multi select field to existing form in Django?
Just like in title. This is what I currently have. I've tried django-multiselectfield but I had many issues with my foreignkey and ManyToMany usage in models. Maybe I should just use a JavaScript or something? I'm a newbie to Django and I really don't know which way to take. After all these hours of helpless work and research I'll consider every proposition. Thank you in advance! MODELS class Category(models.Model): name = models.CharField(max_length=50, unique=True) def __str__(self): return f'{self.name}' class Expense(models.Model): class Meta: ordering = ('date', '-pk') category = models.ForeignKey(Category, null=True,blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=50) amount = models.DecimalField(max_digits=8,decimal_places=2) date = models.DateField(default=datetime.date.today,db_index=True) def __str__(self): return f'{self.date} {self.name} {self.amount}' FORMS class ExpenseSearchForm(forms.ModelForm): GROUPING_CHOICES = ('date', 'category asc', 'category desc') grouping = forms.ChoiceField(choices=[('', '')] + list(zip(GROUPING_CHOICES, GROUPING_CHOICES))) SORTING_CHOICES = ('date asc', 'date desc' ) sorting = forms.ChoiceField(choices=[('', '')] + list(zip(SORTING_CHOICES, SORTING_CHOICES))) class Meta: model = Expense fields = ('name','category') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for i in self.fields: self.fields[i].required = False -
Python print a value that does not exist in a filter
I have some code that filters a mailbox to see if certain subjects exists. How can I print the subject that does not exist in the Queryset? Here is my code: query = (Q(subject__icontains='Backup - no index - Friday') | Q(subject__icontains='backup - with no index Thursday')) if not testfolder.filter(query, datetime_received__gt=since, sender='email@email.dk').exists(): print('we are missing a backup') else: print('email found') -
How can I store files in Django
How can I be able to store files in Django in a model? Well, I know about the FileField but I don't understand how it works the thing is that I want to be able to store the file and no the path cause like I am making a cloud storage website for a project and want to be able to store the file. And how could I be able to change the file name when a user wants to change it. -
How to do scheduling task in django and selenium combine project?
I am working on a web app project in Django with selenium where per one user there is one chrome browser open also chrome profile directory per user and chrome stay alive 24/7. Where the user can send msg or schedule msg. My problem is how can I send a schedule msg. The following problem I am facing while working on my project: How to open a browser that already associated with my user because I already have user chrome profile directory per user and chrome is always open. I want that user webdriver id. My doubt: can I need to make different python project for scheduling task or I can make script inside Django project that work 24/7 checking for scheduling msg for all user? What I want: I want to make a script that runs every 5 min check for scheduling msg if there are any scheduling msg then open user chrome that already open (maybe u think how I know which chrome? ans: because I save chrome profile folder with my user id and u can access same chrome with user profile so I don't need to log in again for that user).In the end all I … -
My Blog Posts disappear everytime is make migrations. Heroku-Django blog
So I made a blog with django and hosted it on heroku(Free version), and every time I make migrations, the posts that I uploaded earlier disappear and the left are the trial posts which I uploaded on my machine for testing. I don't understand why this is happening. These are the commands I used. heroku run python manage.py makemigrations and then heroku run python manae.py migrate I don't think that it is any code that is throwing this problem. But if you need to check any of the file, I'll attach it. Please help. -
How to get around Django redirecting all http requests as GET requests, when using SECURE_SSL_REDIRECT
it looks like when django is using SECURE_SSL_REDIRECT, it redirects all http requests to GET requests, regardless of what the initial method was. is there any way to maintain the body & header during the redirect? -
django: Display anchor link on template using Jinja if statement
I made a friends system in Django. I created a profile model for every user and it has a friend field. I also created a friendrequest model to send and receive request. Everything works fine. On every user's profile(a model) I can see three options: Add friend, remove friend and cancel request. But I only wanna show the add friend link if the user who's profile I'm on is not a friend of mine. The same for remove friend and cancel request(if the FriendRequest object exists then display the cancel request). I tried to check if the user who's profile I'm on is a friend of mine, if he is, the profile should display a remove friend option but the thing is not working. Here's my code: My models.py: class profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') desc = models.TextField(null=True) pfp = models.ImageField(default='social_media/images/profile.jpg', upload_to='profile_pics/', null=True, blank=True) cover = models.ImageField(default='social_media/images/cover.jpg', upload_to='cover_pics/', null=True, blank=True) occupation = models.CharField(max_length=250, default='') friend = models.ManyToManyField(User, blank=True, null=True, related_name='friended') def __str__(self): return self.user.username class FriendRequest(models.Model): to_user = models.ForeignKey(User, related_name='to_user', on_delete=models.CASCADE) from_user = models.ForeignKey(User, related_name='from_user', on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) # set when created def __str__(self): return "From {}, to {}".format(self.from_user.username, self.to_user.username) My view to display the profile: @login_required def … -
ValueError at /ads/ad/2/comment
I am trying to add comment to an Ad posted by a user. When I press the comment button, it is showing the error. Here's my models.py from django.db import models from django.core.validators import MinLengthValidator from django.contrib.auth.models import User from django.conf import settings class Ad(models.Model): title = models.CharField( max_length=200, validators=[MinLengthValidator(2, "Title must be greater than 2 characters")] ) price = models.DecimalField(max_digits=7, decimal_places=2, null=True) text = models.TextField() owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) #picture picture = models.BinaryField(null=True, blank=True, editable=True) content_type = models.CharField(max_length=256, null=True, help_text='The MIMEType of the file') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) comments = models.ManyToManyField(settings.AUTH_USER_MODEL, through='Comment', related_name='comments_owned') #show up in the admin list def __str__(self): return self.title class Comment(models.Model) : text = models.TextField( validators=[MinLengthValidator(3, "Comment must be greater than 3 characters")] ) ad = models.ForeignKey(Ad, on_delete=models.CASCADE) owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) # Shows up in the admin list def __str__(self): if len(self.text) < 15 : return self.text return self.text[:11] + ' ...' Here's my forms.py # commentForm from django import forms from ads.models import Ad, Comment from django.core.files.uploadedfile import InMemoryUploadedFile from ads.humanize import naturalsize from django.core import validators from django.core.exceptions import ValidationError ... class CommentForm(forms.Form): comment = forms.CharField(required=True, max_length=500, min_length=3, strip=True) class Meta: model = Comment … -
Search in Class Based ListView | Django
I am trying to search items in cbv. Though it's too easy with function based views but I don't know how to use it in CBV. I tried like this views.py class HomeView(ListView): model = Item #query = request.GET.get("q") def get_context_data(self, **kwargs): context = super(HomeView, self).get_context_data(**kwargs) query = self.request.GET.get('q') if query: context['model'] = Item.objects.get(title=query) print(query) return context paginate_by = 5 template_name = "home.html" home.html <form class="form-inline my-2 my-lg-0" method="GET" action=""> <input class="form-control mr-sm-2" type="text" name="q" placeholder="Search" value="{{ request.GET.q }}"> </form> The problem is it's showing all items( not specifically searched items ). Example: in url http://127.0.0.1:8000/?q=Blue it is not only showing the item with Blue title but all items. -
Make django query from database based on two models
I am working on search page in which doctor can search for patient with name ,start_date and end_date. Here start_date and end_date are the date range in which any document was uploaded. The result should return all the patients whose name is name and has documents uploaded between start_date and end_date. class Document(models.Model): name = models.CharField(max_length=15, blank=True) document = models.FileField(upload_to='documents/') uploaded_at = models.DateTimeField(auto_now_add=True) patient = models.ForeignKey(to=Patient, on_delete=models.CASCADE, unique=False) class Meta: unique_together = ('name', 'document', 'patient') # many document can have same patient def __str__(self) -> str: return f'{self.name}' def __repr__(self) -> str: return f'{self.name}' class Patient(models.Model): # required fields first_name = models.CharField(max_length=55, blank=False, null=False) last_name = models.CharField(max_length=55, blank=False, null=False) email = models.EmailField(max_length=255, blank=False, null=False, unique=True) # not required fields address = models.TextField(max_length=255, blank=True, null=True) postal_zip = models.IntegerField(max_length=255, blank=True, null=True) city = models.CharField(max_length=255, blank=True, null=True) country = models.CharField(max_length=255, blank=True, null=True) phone_number = models.IntegerField(max_length=17, blank=True, null=True) # mobile alternate_number = models.IntegerField(max_length=17, blank=True, null=True) # alternate def __str__(self) -> str: return f"{self.first_name} {self.last_name}" def __repr__(self) -> str: return f"{self.first_name} {self.last_name}" I can get all documents uploaded between particular dates like this documents = Document.objects.filter( uploaded_at__gte=start_date ).intersection( Document.objects.filter(uploaded_at__lte=end_date) ) but I cant figure out a way to combine above result with this query = … -
Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output - while installing pycopy-fcntl through pip
I was trying to install pycopy-fcntl via pip package installer but it was giving this error(newbie in stackoverflow). ERROR: Command errored out with exit status 1: command: 'c:\users\lg\appdata\local\programs\python\python37\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\lg\\AppData\\Local\\Temp\\pip-install-bjhg1nur\\pycopy- fcntl\\setup.py'"'"'; __file__='"'"'C:\\Users\\lg\\AppData\\Local\\Temp\\pip-install- bjhg1nur\\pycopy-fcntl\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open) (__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\lg\AppData\Local\Temp\pip-pip-egg-info- 00tiv3i6' cwd: C:\Users\lg\AppData\Local\Temp\pip-install-bjhg1nur\pycopy-fcntl\ Complete output (5 lines): Traceback (most recent call last): File "<string>", line 1, in <module> File "c:\users\lg\appdata\local\programs\python\python37\lib\tokenize.py", line 447, in open buffer = _builtin_open(filename, 'rb') FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\lg\\AppData\\Local\\Temp\\pip-install-bjhg1nur\\pycopy-fcntl\\setup.py' ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. I had tried this code pip install --upgrade setuptools still the error arrives. I can't understand, what is the error telling about? Thanks in advance, Sir/Mam. -
Update an object which has a nested object with depth option set
I'm sure the question can be modified to sound clear. I have some models; List, ListItems as: class List(models.Model): name = CharField() active = Boolean() created = DateTime(auto_add) updated = DateTime(auto_update) author = ForeignKey(CustomUser) class ListItems(models.Model): name = ... List = ForeignKey(List) associatedItem = ForeignKey(someModel) active = ... created = ... updated = ... And their serializers as: class ListItemSerializer(serializers.ModelSerializer): class Meta: model = ListItem depth = 2 # because I want the details about `associatedItem` in the serializer too. fields = "__all__" class ListSerializer(ModelSerializer): listitem_set = ListItemSerializer(many=True) class Meta: model = List fields = "__all__" def create(self, validated_data): # Create new List object # and get listitem_set from validated_data and create it and associate with current List def update(self, instance, validated_data): # pop listitem_set from validated_data, create new ListItem for each of them # update instance accomodating validated_data Consuming the serializers are smooth, the issue arises when I try to create/update the List. When I pass data like: { "name": "SomeList", "active": true, "author" : 1, "listitem_set": [ { "name": "ListItem1", "active": true, "associatedItem": 32 } ] } I get error specifying: IntegrityError NOT NULL constraint failed: list_listitem.associatedItem_id. I hope the question makes sense. Let me know if I … -
Django - render two pages on same view
I'm a newbie on web dev and I am developing a Django app. Right now I have a home page and a button to redirect to another page triggering the view. This view has code to update the database which takes a considerable amount of time to complete. So I divided the main run into two steps. My goal is to when the user clicks the redirect button on the home page take him to a page that shows outdated data from the database, in this new page automatically update the database (long-lasting code execution), and then refresh the page with the new values. In short: Home Page -> Outdated data page -> Update database -> Refresh page with new values views.py # initialRun() just gathers initial info before major run def allgames_view(request, *args, **kwargs): listUrl, data = betchamp.initialRun(0, False) return render(request, "games/allgames.html",{}) #page with outdated data from database (in progess) Don't know where to put this: # major run (main) and then check if the object is to be updated or created data = betchamp.main() for match in data['Games']: try: obj = Game.objects.get(game=match['game'], date=match['date']) print(obj.game) print(obj.numberTips) print(match['numberTips']) if match['numberTips'] > obj.numberTips: obj.numberTips = match['numberTips'] obj.ProbAway = match['ProbAway'] obj.ProbHome = … -
(Django Rest Framework) How to add backward URL field?
I'm using drf-nested-routers. Parameter and Location are connected by _location foreign key. Inside Parameter, I want to add a Location field that points to its Location. I think what I need is a backward url link? How could I achieve this? model class Location(models.Model): name = models.CharField(max_length=25, unique=True) description = models.CharField(max_length=64, blank=True) longitude = models.FloatField(blank=True, null=True) latitude = models.FloatField(blank=True, null=True) class Meta: verbose_name_plural = 'locations' def __str__(self): return self.name class Parameter(models.Model): name = models.CharField(max_length=25) unit = models.CharField(max_length=10, blank=True) values = models.JSONField(default=list, blank=True) _location = models.ForeignKey(Location, on_delete=models.CASCADE, related_name="parameters" ) def __str__(self): return self.name serializer class ParameterSerializer(serializers.ModelSerializer): aggregation = serializers.SerializerMethodField() #I want to add the location url here location = class Meta: model = Parameter fields = ('id', 'name', 'unit', 'aggregation', 'location', 'values') def get_aggregation(self, obj): return aggregate(obj.values) def create(self, obj): return add_parameter(obj) class LocationSerializer(serializers.ModelSerializer): parameters = serializers.HyperlinkedIdentityField(view_name='weather:location-parameters-list', lookup_url_kwarg='location_pk') aggregation = serializers.JSONField(default=dict, source="parameters.aggregation", allow_null=True) class Meta: model = Location fields = ('id','name', 'description','longitude', 'latitude', 'aggregation', 'parameters') def create(self, obj): return add_location(obj) urls.py app_name = "weather" router = routers.SimpleRouter() router.register('locations', LocationViewSet) locations_router = routers.NestedSimpleRouter(router, 'locations', lookup='location') locations_router.register('parameters', ParameterViewSet, basename='location-parameters') urlpatterns = [ path("", include(router.urls)), path("", include(locations_router.urls)) ] -
How can I create an object of Bid Model and initialise it whenever I create an object of Listing Model through views.py
Models.py from django.contrib.auth.models import AbstractUser from django.db import models class Listing(models.Model): title = models.CharField(max_length=64) description = models.CharField(max_length=64) base_price = models.IntegerField(null=True) current_price=models.IntegerField(default=False) category = models.CharField(max_length=50) pub_date = models.DateTimeField(auto_now_add=True) img_link = models.CharField(max_length=100) owner = models.CharField(max_length=64) class Bid(models.Model): current_bid = models.IntegerField() listingid = models.IntegerField(default=False) user = models.CharField(max_length=50) views.py def submit(request): if request.method == "POST": listtable = Listing() now = datetime.now() dt = now.strftime(" %d %B %Y %X ") listtable.owner = request.user.username listtable.title = request.POST.get('title') listtable.description = request.POST.get('description') listtable.category = request.POST.get('category') listtable.base_price = request.POST.get('base_price') listtable.current_price = request.POST.get('base_price') if request.POST.get('img_link'): listtable.img_link = request.POST.get('img_link') else: listtable.img_link = "https://i.pinimg.com/originals.jpg" listtable.pub_date = dt listtable.save() return redirect('index') else: return redirect('index') My main concern is to initialise & interlink an object of the Bid model with Listing model and whenever I create an object of Listing Model , an another object should be made of Bid model and it should be initialised with the help of Listing object at the time of its creation -
PostgreSQL Hstore field - key contains string
I am using Hstore data in my PostgreSQL database with my Django application. Keys for hstore field are generated through the process and contain a 10 digit number. Values are decimal numbers. In my SQL Query I do the following to summarize entries for a particular key: SELECT SUM((entries->'0123456789')::numeric) FROM public.appname_model WHERE entries ? '0123456789'; Is it possible to summarize all hsore entries data that would contain first 8 digits, something like: entries ? '01234567%'; Thank you -
I have an unclosed tag 'block' error message but can't see why
I cannot see why this is occurring. I've checked for spelling errors and misplaced spaces but can't understand why I have an undisclosed tag error. Here is the offending code: {% extends "base.html" %} {% block title %}Dashboard{% endblock title %} {% block content %} The error message is "Unclosed tag on line 5: 'block'. Looking for one of: endblock." Line 5 is the 'block content'. Other pages with the same code load perfectly well. -
Yet another NoReverseMatch Reverse for 'login' with no arguments not found error message
My original code works perfectly: html <a class="nav-link" href="/users/login/">Going solo</a> urls path('login/', views.LogIn.as_view(), name='login'), views class LogIn(View): url = "users/login.html" form_context = { 'login_form': LoginForm, } def get(self, request): context = self.form_context return render(request, self.url, context) However, if I introduce a parameter into the url: html <a class="nav-link" href="/users/login/solo/">Going solo</a> urls path('login/<str:next_url>/', views.LogIn.as_view(), name='login'), views class LogIn(View): url = "users/login.html" form_context = { 'login_form': LoginForm, } def get(self, request, next_url): context = self.form_context return render(request, self.url, context) I get the dreaded error Reverse for 'login' with no arguments not found. 2 pattern(s) tried: ['users/login/(?P<next_url>[^/]+)/$', 'duo/login/(?P<next_url>[^/]+)/$'] I have the feeling that this error message does not mean what it says. If someone could explain why it occurs I would be grateful. -
Custom render method in django model that is callable from the template
I would like my django model to offer a render method that could be called from django template. I have tried to achieve this with template nodes with following code. # models.py class PaymentNode(template.Node): def __init__(self, title): self.title = title def render(self, context): return 'payment of ' + context['saldo'] + '€: ' + self.title # Here we could render a template etc. class BankPayment(models.Model): title = 'Bank Payment' def render_payment(self): return PaymentNode(self.title) Then, in the views.py I could inject different payment models and the saldo, that is used in the payment type rendering, into the context # views.py class MyView(TemplateView): def get_context_data(self, *args, **kwargs): ctx = super().get_context_data(*args, **kwargs) ctx['payments'] = [ BankPayment() ] ctx['saldo'] = 10 return ctx In the template I would like to render all payments like this: Pay {{ saldo }} using one of these: <ul> {% for p in payments %} <li>{{ p.render_payment }}</li> {% endfor %} </ul> This should have outcome of payment of 10€: Bank Payment. But django template does not render the Node, it just outputs <models.PaymentNode object at 0x7ffb52054668> Is it possible to do this? It doesn't have to be template.Node but I would like to access the context in the rendering … -
How to set new comment notifications alert for all pages in django?
Currently I'm trying to use signals to send notificaions if users get new comments. In website design, I set a base.html as the basic menubar loader. In the menubar there is a user avatar where I want to put numbers if users get new notifications. I tried to pass the notification numbers directly to the base.html but it can be seen only in that page and disappeared in other pages. So does anyone know how to realize this function? Models.py class Alert(models.Model): sender = models.ForeignKey(UserProfile, on_delete=models.CASCADE, related_name="sender_userprofile", verbose_name="Sender") receivers = models.ForeignKey(UserProfile, on_delete=models.CASCADE, related_name="receivers_userprofile", verbose_name="Receiver") timestamp = models.DateTimeField("Created Time", auto_now_add=True) is_read = models.BooleanField('Is read', default=False) belong_cmt2mess = models.ForeignKey(CommentToMessage, on_delete=models.CASCADE, related_name="belong_and_mess",verbose_name="Comments belonged") class Meta: verbose_name = 'Notifications' verbose_name_plural = verbose_name ordering = ['-timestamp'] def mark_read(self): self.is_read = True self.save(update_fields=['is_read']) @receiver(post_save, sender=CommentToMessage) def create_msg_handler(sender, instance, **kwargs): b_mess = instance.tar_mess sender = instance.com_nicknames receivers = instance.tar_mess.message_nicknames msg = Alert(sender=sender, belong_mess=b_mess, receivers=receivers, belong_cmt2mess=instance) msg.save() -
Django - how to store this data?
I have conceptual problem, and I have no big experience with django, so I'd like to ask here. I have django model, and I want to show it in frontend (in like chart or sth like that). However, earlier I would like to add some parameters to it (some int values that will be relevant on chart). Here I have three options: make another model with ForeignKey - but this model would never be saved in database, make form - but I feel like forms are made for getting data and here I would like to show them on view, make a normal class - but it's django ... So which do you think in django works best?