Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Associate database with an user using "uuid"
I have a desktop app which adds data to a database when user does the ctrl +c , ctrl +alt+c combination and it sends e-mails about the data to the user every x time. What I wanna do is build a django app, connect it to the same database with the desktop app. The scenario I want to built ;user gives an e-mail address to the web app , the web app gives an uuid to the user then starts the download of the desktop app, the user types that uuid on the desktop app,the desktop app connects to the database on cloud , user adds data to the database on the cloud using the desktop app. E-mail sender sends datas to the e-mail addresses using the database every x time . -
Efficiently retrieve from and add to ManyToManyField
I have two models, let's say Container and Item. Container has a ManyToMany field to associate Containers to Items. I want to add an Item to a Container and then list all of the Items in this container. However, I've noticed that Django queries for each item before it adds it, therefore I end up with three queries, one to get all of the Items, one to check if the Item I want to add is there, and another to add the Item. Is there a way to eliminate this superfluous checking? I've tried replacing the item_set entirely using the set command but it still adds the extra check for duplicates. # Select all items in item_set existing = container.item_set.all() # Select item in item_set (even though we know) and insert item into set container.item_set.add(new_item) In brief: I would like to end up with a new item added to the set and all the old items from the set in two queries -
Django client-side form validation of regexvalidator doesn't work
I have implemented Django model+form that I would like to validate on client side. Every constraint is validated perfectly as expected apart from a RegexValidator. The regex itself works fine in Python and JS alike. I believe the problem is that the validation does not propagate from Django's model/form to the front layer. I.e. the validation of regex on client's side does not even start. I have found a lot of similar questions here but none of the answers helps. For example here people advice using EmailValidator (can't since its not an email or any other specialized field), using parsley (I already use django-angular that would probably colide), or validate in HTML (I would really like to keep the DRY principle). Writing my own validator or naming parameters don't help either. Is there any way how to validate RegexValidator on client's side without third-party libraries? # models.py class Contact(models.Model): firstname = models.CharField(max_length=254) lastname = models.CharField(max_length=254) address = models.CharField(max_length=254) email = models.EmailField(max_length=254) phone_regex = RegexValidator(regex=r'^\+\d{8,15}$', message="Phone number must be entered in the format: '+99999999'. Up to 15 digits allowed.") phone = models.CharField(max_length=16, validators=[phone_regex]) # forms.py class ContactForm(forms.ModelForm): class Meta: model = Contact fields = ('firstname', 'lastname', 'address', 'email', 'phone') # views.py … -
When published django-cms plugin from edit mode html template doesn't render model objects. But content reappears when switched to edit mode
Actually, I am new to Django-cms world. I tried almost every duplicate of this same question but none of them worked. I have created my custom plugin with just one ManyToManyField(). I went through Django-docs For many-to-many or foreign key relations to other objects but that didn't helped. Maybe I am lost somewhere, I would really appreciate any help. Thank you. Try1 PluginModel : class PortfolioPluginModel(CMSPlugin): portfolio = models.ManyToManyField(Portfolio) Try2 PluginModel : class PortfolioPluginModel(CMSPlugin): portfolio = models.ManyToManyField(Portfolio) def copy_relations(self, oldinstance): for p in oldinstance.portfolio.all(): p.pk = None p.plugin = self p.save() Try3 PluginModel : class PortfolioPluginModel(CMSPlugin): portfolio = models.ManyToManyField(Portfolio) def copy_relations(self, oldinstance): self.portfolios = oldinstance.portfolios.all() Apps Model: class Portfolio(models.Model): author = models.CharField(max_length = 100) description = models.TextField() image = models.ImageField(upload_to ='portfolioImage',blank = True, null = True) published_at = models.DateTimeField(auto_now_add = True) cms_plugins.py @plugin_pool.register_plugin # register the plugin class PortfolioPluginPublisher(CMSPluginBase): model = PortfolioPluginModel # model where plugin data are saved # model = Portfolio(CMSPlugin) module = _("Portfolio") name = _("Portfolio Plugin") # name of the plugin in the interface render_template = "portfolio_cms_integration/portfolio_plugin.html" cache = False def render(self, context, instance, placeholder): context.update({'instance': instance}) return context portfolio_plugin.html <div class="filters-content"> <div class="row grid"> {% for p in instance.portfolio.all %} <div class="single-portfolio col-sm-4 all vector"> … -
Why do I get 'CSRF Token Missing or Incorrect' error for Javascript Request
I am trying to create request in Javascript when a button is clicked but instead receive the error Forbidden (CSRF token missing or incorrect.). I have included {% csrf_token %} in the HTML template: <form action="/cart" method="POST"> {% csrf_token %} <button type="button" id="ordered">Place Order</button> </form> But am unsure if I have to include it in my Javascript request: const request = new XMLHttpRequest(); request.open("POST", "/cart"); // send request let data = new FormData(); items = localStorage.getItem(user + "items") total = localStorage.getItem(user + "price") data.append("items", items) data.append("total", total) request.send(data); In my views.py: def cart(request): if request.method == "POST": data = request.get_json() print(f"{data}") return HttpResponseRedirect(reverse("index")) else: return render(request, "cart.html") -
Authentication with Vue JS and Django?
I'm working on a small university project with Vue JS, Django2, Django Rest Framework where I have 2 differents rol for the users so they can do differents action in the application. I'm confused on the login part. I don't know how work with both frameworks(Vue and django) for the authentication in my project. I've read about JWT, I understand how it works but I haven't used before. If there is not another way to work with the auth I'll user JWT. Is there another way to work with authentication with both frameworks? -
Django: Populating serialized field if model field's foreign key relationship exists
Let's say I have 3 models: class MeterialPricing(models.Model): list_price = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) book_pricing = models.ForeignKey('books.BookPricing', null=True, blank=True) inventory_pricing = models.ForeignKey('store.InventoryPricing', null=True, blank=True) class BookPricing(models.Model): list_price = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) class InventoryPricing(models.Model): list_price = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) And a serializer class: class MaterialPricingSerializer(ModelSerializer): class Meta: model = MaterialPricingShell fields = ('pk', 'list_price',) As you can see, right now, the serialized list_price is coming from the MaterialPricing model. If BookPricing or InventoryPricing list_price exists, I want to set the serialized list_price to be one of these. The list_price in BookPricing has the most priority, then the InventoryPricing, and if both of these are null, then we can just have the list_price be the list_price on the MeterialPricing model. I was looking into using SerializerMethodField(), but I'm not sure if there is a post hook of something kind to look if the list_price exists on the BookPricing or InventoryPricing models. -
urlconfig - It takes Default parameter, not the passing one
if I pass http://127.0.0.1:8000/call/?p=3 and i print num in view.page it prints 1 #urls.py urlpatterns = [ path('call/',views.call), path('call/page<int:num>/',views.call), ] if I pass 127.0.0.1:8000/call/?p=3 and it prints num 1 and not 3. # View (in blog/views.py) def page(request, num=1): print(num) // 1 -
CSRF Cookie not set error on React Native Front end with Django Back end
I have a react native application which has Django as it's back end. I am using django-allauth along with django-rest-auth to handle social login in the app. In the app, apart from Social Login/Signup, a user can also do the regular sign up using email and password. The API for Regular Sign Up works every time as many times it is being called,a new user is being created on the DB. When signing up via Facebook, the user is created on the DB. But after this first successful hit, all of the hits that follow are met with 403 Forbidden with a message CSRF (Cookie/Token[I don't remember the error]) not set. And even the regular sign up API also starts receiving this same error. Both the React Native Development Workstation and Django Backend workstation are on the same network. I have tried csrf_exempt but it does not have any effect.Is it due to improper logout ? What other things am I missing with respect to django-allauth/django-rest-auth library ? Any help would be appreciated. -
can I serve a python 2.7 and a 3.6 django website at the same time with the same User database?
I have an old python 2.7 with Django 1.8 website running for years, it would be a lot of works to do if I upgrade it to python 3 and a new version Django, since there are a lot of apps on it not compatible with python 3. And I need to use channels. It looks like I'd better use python 3.6+ and the new version of Django. So I could only create a new site rather than create an app for the old website. Can I serve a new website, and share the old database to it so that the users can use the new one directly? -
Django: Why is my ModelForm not displaying any value to my instance?
I have created a modelform with a single text field. I instantiate this with my model object. When I render my form, there is no field with my object PK. Therefore how does the form know which model object it refers to? forms: class InterForm(forms.ModelForm): inter = forms.CharField( widget=forms.Textarea(attrs={'rows': 6, 'cols': 160}), label='', required=True) class Meta: model = Sample fields = ('id', 'interpretation',) def __init__(self, *args, **kwargs): super(InterForm, self).__init__(*args, **kwargs) views: interpretation_form = self.interpretation_form(instance=self.crs_obj) display: <tr><th></th><td> <textarea name="interpretation" cols="160" rows="6" required id="id_interpretation"> </textarea></td></tr> why doesnt this have my id as the PK displayed by the form? So when I submit it the model object can be saved with the interpretation field? -
Simple Django Join
I'm quite frustrated by now. I'm trying to do a really simple query to two models. My goal is simply to join A and B, in SQL I would do it like: SELECT * FROM A JOIN B ON A.x = B.z My models look roughly like class A(models.Model): x = id class B(models.Model): z = ForeignKey(A) I want a cross product from A and B and not just a filter. Can please somebody help me out? I'm sure the solution is more than obvious but I can't find it. -
How can I get a form field attribute from within the form element and use it's value to set a nested div's id?
I am new to Django and am struggling with the modelformset. I have read the documentation and looked through StackOverflow, etc. and cannot seem to find a solution to the following problem. I have a Django modelformset in my template, the forms of which I display with a for loop. I would like to display each form in its own div and I would like each div to have a unique id which relates it to the form it contains -- to do this I have a "form_id" field in the model the modelformset uses (the field is hidden to the user) that I want to access and use to dynamically assign a value to the div's id (see template code below). However, I cannot seem to access the form's "form_id" field for use in the div id. {% for form in incident_formset %} <div id=""> <fieldset> <legend>Report</legend> {% crispy form %} <input type="button" id="" value="Delete Report"> </fieldset> </div> {% endear %} In the above code, I would like to have the id of the divs to be "form_form_field_value" and "delete_form_form_field_value" respectively. I have tried getting the value with form.form_id.value among other combinations and concatenating that value with the id … -
How to force two buttons into one line
Below you see the cell where the buttons (bootstrap 4) are. The other cells were not printed. The EDIT and DELETE button are one over the other (2 lines). How to force them to the same line? <div class="container"> <table class="table table-striped"> ..deleted... <tbody> ..deleted... <tr> <div> <form method="GET"> {% csrf_token %} <button class="btn btn-outline-secondary btn-sm" type="submit" name="edit" value={{objekt.id}}>Edit</button> </form> <div id="colwrap"> <form method="POST"> {% csrf_token %} <button class="btn btn-outline-secondary btn-sm" type="submit" name="delete" value={{objekt.id}}>Delete</button> </form> </div> </div> </tr> </tbody> </table> </div class="container"> -
How to create a table with two fields as User model type
I'm trying to make a messaging app in my django project, I want the table to have three fields, "sender" "title" "message" "reciever". Title and Message can be declared as char-field. But I cannot make sender and receiver as two ForeignKey Field. I don't know what to use here. Can anyone help me figure this out? I tried to declare both field as ForeignKey with user model. But it didn't worked. from django.db import models from django.contrib.auth.models import User # Create your models here. class msgs(models.Model): to = models.OneToOneField(User, on_delete=models.CASCADE) frm = models.OneToOneField(User, on_delete=models.CASCADE) title = models.CharField(max_length = 255) body = models.CharField(max_length=2000) ERRORS: msgs.msgs.frm: (fields.E304) Reverse accessor for 'msgs.frm' clashes with reverse accessor for 'msgs.to'. HINT: Add or change a related_name argument to the definition for 'msgs.frm' or 'msgs.to'. msgs.msgs.frm: (fields.E305) Reverse query name for 'msgs.frm' clashes with reverse query name for 'msgs.to'. HINT: Add or change a related_name argument to the definition for 'msgs.frm' or 'msgs.to'. msgs.msgs.to: (fields.E304) Reverse accessor for 'msgs.to' clashes with reverse accessor for 'msgs.frm'. HINT: Add or change a related_name argument to the definition for 'msgs.to' or 'msgs.frm'. msgs.msgs.to: (fields.E305) Reverse query name for 'msgs.to' clashes with reverse query name for 'msgs.frm'. HINT: Add or … -
Gel all the values of Many2Many intermediate table with their respective name
I have the following database structure: Products -------- id name 1 prodA 2 prodB Products_Invoices ----------------- product_id Invoice_id 1 1 2 1 Invoices -------- id name 1 InvA 2 InvB Which is most correct way to retrieve all the values of the Products_Invoices table but bring the names of their respective row in parent tables. -
How to fix 'Not found The requested resource was not found on this server.', faced when serving django website using nginx?
I have hosted my website www.gojainyatra.com made with django, served using nginx. While some of the pages are opening correctly, there are some pages which give error, e.g. https://www.gojainyatra.com/dharamshala/firstshala/vlogs/2019/6/20/5/9/46/test/ Not found The requested resource was not found on this server My nginx configuration: upstream app_server { server unix:/home/gojainyatra/run/gunicorn.sock fail_timeout=0; } server { listen 80; server_name gojainyatra.com www.gojainyatra.com; keepalive_timeout 5; client_max_body_size 4G; access_log /home/gojainyatra/logs/nginx-access.log; error_log /home/gojainyatra/logs/nginx-error.log; location /static/ { alias /home/gojainyatra/staticfiles/; } # checks for static file, if not found proxy to app location / { try_files $uri @proxy_to_app; } location @proxy_to_app { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://app_server; } } I don't know why this is happening, please help. -
Django Many Users to One model. A Model about the User
I'm trying to figure out how the many users can be associated with one instance of a model. I have a sports club project. There is many users (admin and staff) only one Club. I can't seem to form a many to one relationship with the User model. I want to filter mainly by club. Say if 3 clubs use the project, each club would want to be separated by club and not by user. Below is a simplified version of my models. I've also tried to add the ForeignKey to the club and go the other way. Class Club(models.model): name = models.CharField(max_length=40, null=True) Class User(AbstractBaseUser): name = models.CharField(max_length=40, null=True) club = models.ForeignKey(Club, on_delete=models.CASCADE) -
Function missing 1 required positional argument(pandas)
I am trying to return a ratio between two tickers but am getting an error when trying to view it locally. I'm new to both pandas and django so any help will be much appreciative. def tkr_ratio(ticker1, ticker2): tickers_dict = TSDB.objects.filter(TICKER__in = [ticker1, ticker2]).values('DATE', 'TICKER', 'CLOSE') df = pd.DataFrame(tickers_dict, columns = ['DATE', 'TICKER', 'CLOSE', 'RATIO']) df = pd.pivot_table(df.sort_values('DATE'), values = 'CLOSE', index = 'DATE', columns = 'TICKER') json_list = [] df['RATIO'] = df[ticker1]/df[ticker2] for i in df['RATIO'].itertuples(): json_list.append([totimestamp("DATE"), i]) return json_list TypeError: tkr_ratio() missing 1 required positional argument: 'ticker2' -
get_FIELD_serializer in Django Rest Framework
I'm in a situation where I want to change the serializer field depending on a condition. Where the condition comes doesn't matter but I want to be able to switch between serializer fields as the following example: class EntrySerializer(serializers.ModelSerializer): # author defined from ModelSerializer def get_author_serializer(self): request = self.context.get('request') GET = getattr(request, 'GET', {}) if request and GET and GET.get('include_author')=='true': author_serializer = UserSerializer() else: author_serializer = serializers.PrimaryKeyRelatedField( read_only=True, default=serializers.CurrentUserDefault() ) return author_serialize Of course this doesn't work because get_FIELD_serializer doesn't exist, but I'm looking for the simplest solution that can do this. I've tried writing author as a property in a naive attempt but it didn't work. I am aware that I can write multiple EntrySerializers and use get_serializer_class but that is just too much boilerplate code for such a small customization. -
Django: Creating query set?
I am trying to get the following outcome <EventQuerySet [{4: 10000, 5: 20000, [...]}]>. The way to "get" there is the following workflow: 1) Get each active event of the organizer def organizers(self): return self.request.user.organizers Event.objects.filter( organizer__in=self.organizers, status=EventStatus.LIVE ) 2) For each event > get all tickets that belong to that specific event. Especially, I need to get access to quantity & price of each ticket 3) Get the amount of tickets which are already sold .annotate( sold_tickets=Count('attendees', filter=Q(attendees__canceled=False)) ) .order_by('organizer') 4) Now we have all the information we need to calculate the max_remaining_gross_sale per event: Example: Event with pk 4 Ticket 1: price_gross * (quantitiy - sold_tickets) Ticket 2: price_gross * (quantitiy - sold_tickets) Event with pk 5 Ticket 1: price_gross * (quantitiy - sold_tickets) [...] 5) From all tickets per event we build the Sum an get the following result: <EventQuerySet [{4: 10000, 5: 20000, [...]}]> I didn't manage to build that QuerySet in a way that gives me the result from 5). Do you have any advice for me? Here my models with the relevant fields: class Ticket(TimeStampedModel): quantity = models.PositiveIntegerField( verbose_name=_("Quantity"), validators=[MinValueValidator(1), MaxValueValidator(100_000)], ) status = models.CharField( max_length=8, choices=TicketStatus.CHOICES, default=TicketStatus.ON_SALE, verbose_name=_("Status"), ) price_gross = models.PositiveIntegerField( verbose_name=_("Price … -
Django Rest doesn't change cookie/sessionid on password change
I want to flush an old cookie and set a new one, so that an old cookie would be invalidated. My method for password changing def update(self, request, *args, **kwargs): self.object = self.get_object() serializer = self.get_serializer(data=request.data) if serializer.is_valid(): # Check old password if not self.object.check_password(serializer.data.get("old_password")): return Response({"old_password": ["Wrong password."]}, status=HTTP_400_BAD_REQUEST) self.object.set_password(serializer.data.get("new_password")) self.object.save() print(self.object) update_session_auth_hash(request, self.object) request.session.flush() return Response("Success.", status=HTTP_200_OK) return Response(serializer.errors, status=HTTP_400_BAD_REQUEST) and my method for logging user in def login_user(self, request, *args, **kwargs): username = request.data.get("username") password = request.data.get("password") if username is None or password is None: return Response({'Result': {'error': 'Please provide both username and password'}}, status=HTTP_400_BAD_REQUEST) user = authenticate(request, username=username, password=password) if not user: return Response({'Result': {'error': 'Invalid Credentials'}}, status=HTTP_400_BAD_REQUEST) if user: login(request, user) return Response({"Result": {'Success': 'Logged in'}}, status=HTTP_200_OK) when i logout it shows that my cookie is change, but whenever I login again it sets an old cookie :/ upd: My settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',), 'COERCE_DECIMAL_TO_STRING': True } STATIC_ROOT = os.path.join(STATIC_URL + 'Test') SESSION_ENGINE = 'django.contrib.sessions.backends.signed_cookies' SESSION_COOKIE_HTTPONLY = True SESSION_SAVE_EVERY_REQUEST = True MIDDLWARE = [... 'django.contrib.sessions.middleware.SessionMiddleware', ....] -
How to add custom ID for Celery task in order to revoke task later?
I want to create delayed task and if there would be some conditions, I need to find that task and revoke it. This is how I create task: notify_before_departure.apply_async( args=(user.fcm_registration_token, booking.bus_stop_from.title,), eta=notification_time, ) So is there any attribute apply_async has where I can define my custom ID which can later be used to revoke this exact task? Something like this: # create task notify_before_departure.apply_async( args=(user.fcm_registration_token, booking.bus_stop_from.title,), eta=notification_time, custom_id=booking.id ) # revoke if needed from celery.task.control import revoke revoke(booking.id, terminate=True) -
Suppress Status Output in Django
I tried to find this, but I'm probably not searching the right way. When I run my Django app, I get a record printed to the error output every time an endpoint is called, similar to: [20/Jun/2019 09:45:37] "GET /analyst/run_session/ HTTP/1.1" 200 1271 The problem is, I have a call set up every second to refresh data from the api, so my console is being flooded by these entries. I have tried setting DEBUG=False, and setting MESSAGE_LEVEL=message_constants.ERROR, but it doesn't seem to suppress these entries. Is there something obvious I'm missing? -
Creating a Django Rest Framework log activity for users that are Reading or Writing to certain APIs
Want a way to log users activity on my api. For example, want to see which users are hitting certain APIs. Also seeing if they're making any changes to the APIs