Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Instagram followersssssss
I didn’t post a fancy and word-playing title. We are all social media brothers and let’s not fool anyone: I follow who follows! Being followed is a very uncomfortable and dangerous situation. In real life. In digital life, the equation is ‘slightly’ different. Which is disturbing and dangerous; not to be followed. Unfamiliarity of followers is not an inconvenience, but a reason for happiness. We don’t get depressed anymore, we look at a friend whose name is ‘disapproval’ and go out. This is the reality of the world – the digital one – whether we like it or not. I also offer a huge service to dear readers for the needs of the day, and this week I am giving tips on how to increase your followers on Instagram. Use labels. If possible, choose those that encourage mutual following, such as #instafollow, #l4l, followback. Follow those who use these tags. Do not neglect the ‘TagForLikes’ application, which allows you to instantly use the most popular tags practically. Like random photos of different people (Don’t always heart beautiful/handsome people, mix trees/plains together. Your girlfriend sees them). In one experiment, it turned out that for every 100 random photos liked, six followers … -
How to append a list in jinja3
I am new to Django and Python. I have a nested forloop in my html template which removes an item from a list with each loop: {% for item in horizontal_list %} {% with vertical_list=vertical_list.pop %} {% endwith %} {% for item in vertical_list %} {{ form.board }} {% endfor %} {% endfor %} The idea behind it is that I am trying to create a hexboard and with the above loop I am able to achieve the following: O O O O O O O O O O O O In other words, the following peace of code is working as expected in the above example: {% with vertical_list=vertical_list.pop %} {% endwith %} However, for the top half of the board, I need a very similar loop but instead of using pop, I need to append the list: {% with vertical_list=vertical_list.append %} {% endwith %} At the moment, it does not append the list and the end result is similar to: O O O O O O <-------- this list here should be appended O O O O O O O O O O O O I am struggling to understand why pop would work in jinja but not … -
What is the best file format for exporting django postgres database
I am working on an app where the user owns a database, I would like to add a feature that allows the user to export his database into various file formats like CSV, JSON, and excel. which of these file formats are the best/easiest to export to while not losing information like metadata? tech used: Django, PostgreSQL -
Djago schedule stuck after While True
After I add this lines, following the schedule docs example, my server stucks and I cant even kill it with ctrl + C, the code is at the very bottom of my app views.py, where should I be adding this while loop command? schedule.every(30).seconds.do(getEvents) while True: schedule.run_pending() time.sleep(1) -
How to set max booking per time If I say I want to set every time an example at 8AM users can book max limit 10 times
models.py class BookingSettings(models.Model): # General booking_enable = models.BooleanField(default=True) confirmation_required = models.BooleanField(default=True) # Date disable_weekend = models.BooleanField(default=True) available_booking_months = models.IntegerField(default=1, help_text="if 2, user can only book booking for next two months.") max_booking_per_day = models.IntegerField(null=True, blank=True) # Time start_time = models.TimeField() end_time = models.TimeField() period_of_each_booking = models.CharField(max_length=3, default="30", choices=BOOKING_PERIOD, help_text="How long each booking take.") max_booking_per_time = models.IntegerField(default=1, help_text="how much booking can be book for each time.") views.py from django import forms from booking.models import BookingSettings class BookingDateForm(ChangeInputsStyle): date = forms.DateField(required=True) class BookingTimeForm(ChangeInputsStyle): time = forms.TimeField(widget=forms.HiddenInput()) class BookingCustomerForm(ChangeInputsStyle): user_name = forms.CharField(max_length=250) user_email = forms.EmailField() user_mobile = forms.CharField(required=False, max_length=10) class BookingSettingsForm(ChangeInputsStyle, forms.ModelForm): start_time = forms.TimeField(widget=forms.TimeInput(format='%H:%M')) end_time = forms.TimeField(widget=forms.TimeInput(format='%H:%M')) def clean(self): if "end_time" in self.cleaned_data and "start_time" in self.cleaned_data: if self.cleaned_data["end_time"] <= self.cleaned_data["start_time"]: raise forms.ValidationError( "The end time must be later than start time." ) return self.cleaned_data class Meta: model = BookingSettings fields = "__all__" exclude = [ # TODO: Add this fields to admin panel and fix the functions "max_booking_per_time", "max_booking_per_day", ] how to set maximum per day user can fill the slot and from where i need to start and how to set functions user can fill up to 10 times then the slot is locked. thank you img url https://imgur.com/0LoKSvj -
I have a bunch of files for a website and don't know how to put them together
I am running windows and working in Pycharm community edition for a website. I would like to run Docker in CE but I have seen that is not possible since it is only reserved for professional use. I have installed Docker desktop but that also doesn't work since you need to have Windows pro. I am basically stuck and don't see a way out. Does anyone have a solution. Maybe if there is an easy way rather than just doing everything manually. -
Django Model M2M Relationship to 2 other models from the same model
Here in my problem, I have a User model, in which a user (login) can be from the “Supplier” company or from “Customer” company. It is a M2M relationship for both sets of tables: User-Customer and User-Supplier. Can I link them this way: company = models.ManyToManyField(Customer, Supplier, on_delete=models.PROTECT, related_name='Users') enter image description here Thanks!! -
How to filter a Django model to display only the logged-in user's data?
Trying to solve this for a week now. How do I filter my model to display only the data assigned to the specific logged-in user? My views.py code below is not working---it's not telling forms.py what it needs to do to accomplish this. I get the error 'ForwardManyToOneDescriptor' object has no attribute 'option1'. It does filter effectively in the template---but I need to use the RadioSelect widget (defined in forms.py) in order to display specific choices that the specific logged-in user must choose from (and I don't think I can---or should---code that in the template). views.py class VoteView(LoginRequiredMixin, CreateView): model = Result form_class = VotingForm template_name = 'users/vote_form.html' *Attempt #1: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['Result'] = Result.objects.all() context['user_specific'] = Result.objects.filter (custom_user=self.request.user) return context *Attempt #2: def get_initial(self): initial = super().get_initial() initial.update({'custom_user': self.request.user}) return initial forms.py class VotingForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) choices = [('1', Result.decision.option1), ('2', Result.decision.option2), ] self.fields['vote'] = forms.ChoiceField(choices=choices, label="Choices", widget=forms.RadioSelect()) class Meta: model = Result fields = ['decision', 'vote'] models.py (if needed) class Result(models.Model): custom_user = models.ForeignKey(CustomUser) decision = models.ForeignKey(Decision) * Decision contains decisions and their choices (like 'option1', 'option2') vote = models.CharField() vote_eligible = models.BooleanField(default=False) -
Django: Call many urls with one button
In Django, I would like to use one button to change multiple (independent) parts of a template. Can I connect one button to multiple urls (or to different views?) I don't want to re-render the complete template -
POST 400 (Bad request) when signing up
I am developing a web application using reactjs and Django and I am getting 400 bad request when trying to sign up. I am trying pass data from reactjs to django through django rest api by post method but there raising this problem. Below is the link to the source code Here is my Signup.js file import React from "react"; import { Button, Form, Grid, Header, Message, Segment, } from "semantic-ui-react"; import { connect } from "react-redux"; import { NavLink, Redirect } from "react-router-dom"; import { authSignup } from "../store/actions/auth"; class RegistrationForm extends React.Component { constructor (props) { super(props); this.state = { username: "", email: "", password1: "", password2: "", userType: "", is_student : true }; this.handleSubmit = this.handleSubmit.bind(this); this.handleChange = this.handleChange.bind(this); }; /*state = { username: "", email: "", password1: "", password2: "", userType: "", };*/ handleSubmit = e => { e.preventDefault(); const { username, email, password1, password2, userType, is_student } = this.state; this.props.signup(username, email, password1, password2, userType, is_student); const signupFormValid = !username?.length || !email?.length || !password1?.length || !password2?.length || !userType?.length ; }; handleChange = e => { this.setState({ [e.target.name]: e.target.value }); }; render() { const { username, email, password1, password2, userType } = this.state; const { error, loading, … -
How to display audio file present in PC using django
I am learning django. I am stuck with this problem. I am making a project that takes a text file and gender as input from user and generates an audio file. I want to show that audio file in a HTML page. For doing this I have written the following code in my views.py file context = {'downaud': fbh} return render(request, 'tutorial/downloadaudio.html', context) Here, fbh is the name of the audio file. I have written the followin code in my downloadaudio.html file. <audio src="../../../{{ downaud }}.wav" controls> Your browser is not supporting this format. </audio> But still I am not getting the desired output. In the terminal I see the following error but I am unable to resolve it. Not Found: /earth.wav Here is the link to my git repository - git repository As I already said I am new to django and some help will be appreciated. -
How to load existing database data into Djano (fixtures, postgresql)
Am trying to load some generated data into Django without disrupting the existing data in the site. What I have: Saved the data as a valid JSON (validated here). The JSON format matches the Django documentation. In previous attempts I also aligned it to the Django documentation here (slightly different field order, the result was the same). Output errors I'm receiving are very generic and not helpful, even with verbosity=3. auto_2022_migration.py file: from django.db import migrations from django.core.management import call_command def db_migration(apps, schema_editor): call_command('loaddata', '/filename.json', verbosity=3) class Migration(migrations.Migration): dependencies = [('workoutprogrammes', '0004_extable_delete_ex_table'),] operations = [migrations.RunPython(db_migration),] JSON file extract (start... end) NB: all my PKs are UUIDs generated from postgresql [{"pk":"af82d5f4-2814-4d52-b2b1-6add6cf18d3c","model":"workoutprogrammes.ex_table","fields":{"exercise_name":"Cable Alternating Front Raise","utility":"Auxiliary","mechanics":"Isolated","force":"Push","levator_scapulae":"Stabilisers",..."obliques":"Stabilisers","psoas_major":""}}] The Error Prompt Operations to perform: Apply all migrations: workoutprogrammes Running migrations: Applying workoutprogrammes.0005_auto_20220415_2021...Loading '/Users/Robert/Desktop/Projects/Powerlifts/src/workoutprogrammes/fixtures/datafile_2' fixtures... Checking '/Users/Robert/Desktop/Projects/Powerlifts/src/workoutprogrammes/fixtures' for fixtures... Installing json fixture 'datafile_2' from '/Users/Robert/Desktop/Projects/Powerlifts/src/workoutprogrammes/fixtures'. Traceback (most recent call last): File "/Users/Robert/Desktop/Projects/Powerlifts/venv/lib/python3.8/site-packages/django/core/serializers/json.py", line 70, in Deserializer yield from PythonDeserializer(objects, **options) File "/Users/Robert/Desktop/Projects/Powerlifts/venv/lib/python3.8/site-packages/django/core/serializers/python.py", line 93, in Deserializer Model = _get_model(d["model"]) KeyError: 'model' The above exception was the direct cause of the following exception:... text continues on... for obj in objects: File "/Users/Robert/Desktop/Projects/Powerlifts/venv/lib/python3.8/site-packages/django/core/serializers/json.py", line 74, in Deserializer raise DeserializationError() from exc django.core.serializers.base.DeserializationError: Problem installing fixture '/Users/Robert/Desktop/Projects/Powerlifts/src/workoutprogrammes/fixtures/datafile_2.json': -
Django-Rest-Framework AttributeError object has no attribute 'id'
I facing this bellow error after trying to input data via DRF File "G:\partshouse\venv\lib\site-packages\rest_framework_simplejwt\tokens.py", line 176, in for_user user_id = getattr(user, api_settings.USER_ID_FIELD) AttributeError: 'TestBookingSerializer' object has no attribute 'id' [17/Apr/2022 02:11:40] "POST /api/testbooking/ HTTP/1.1" 500 17894 Serializer.py class TestBookingSerializer(serializers.ModelSerializer): class Meta: model = PendingBooking fields = ['booking_id', 'cus_name', 'cus_unique_id', 'created_by', 'date', 'loading_date_time', 'unloading_date_time', 'due_amount', 'trip_profit', 'ph_number', 'cargo_weight', 'vehicle_type', 'loading_address', 'trip_distance', 'unloading_address', ] hear I cus_name as user name which is the user customer can login View class TestAPIBookingOnly(APIView): renderer_classes = [UserRenderers] permission_classes = [IsAuthenticated] def post(self, request, format=False): serial = TestBookingSerializer(data=request.data, partial=True) if serial.is_valid(): token = get_tokens_for_user(serial) serial.save() return Response({'token': token, 'msg': 'Data Entry Successful', }, status=status.HTTP_200_OK) return Response(serial.errors, status=status.HTTP_400_BAD_REQUEST) -
how to setup webhook on pythonanywhere using "python telegram bot" library
can anyone help me? I am deploying my ready bot to pythonanywhere, locally my webhook was working but on pyanywhere I am getting 404 error on getWebhookInfo. I posted my codes and screenshots Here: https://github.com/python-telegram-bot/python-telegram-bot/discussions/2952 -
Difficulties with axios POST request on material-ui & Django
I am working a project with react.js & material-table as frontend, and django as backend. Currently, I am trying to perform CRUD operations on the material-table. The axios PUT and DELETE requests went pretty well. However, I have some problem with the axios post request. My code below: export default function DataWorker() { const [entries, setEntries] = useState({ data: [ { id: "", position: "", defect: "", tool: "" } ] }); const [state] = React.useState({ columns: [ { title: "Position", field: "position", width: 150, // lookup: { 1: "Position 1", 2: "Position 2", 3: "Position 3"}, cellStyle: { textAlign: "center" } }, { title: "Defect Type", field: "defect", width: 150, // lookup: { 1: "None", 2: "Spalling", 3: "Scratch", 4: "Crack"}, cellStyle: { textAlign: "center" } }, { title: "Tool Decision", field: "tool", width: 150, // lookup: { 1: "None", 2: "Tool 1", 3: "Tool 2", 4: "Tool 3"}, cellStyle: { textAlign: "center" } } ] }); const url = "http://127.0.0.1:8000/api/manual_ver_data/" useEffect(() => { axios.get(url) .then(response => { let data = []; response.data.forEach(el => { data.push({ id: el.id, position: el.position, defect: el.defect, tool: el.tool }); }); setEntries({ data: data }); }) .catch(function(error) { console.log(error); }); }, []); return ( … -
Can i add a python variable in css?
I have a django template loop running on my website. Here's the code for reference: <div class="col-6"> <center><i><u><h3 class="text-centre">Live News from The Toronto Star</h3></u></i></center> {% for n, i in toronto %} <img src="{{i}}"> <strong><h5>{{n}}</h5></strong> <hr> {% endfor %} <br> </div> I now want to design it differently and want to remove the <img> tag and put the i variable as the background of the <h5> element. How would i put a python variable inside a css property? Is that even possible? ( the background-image property for example? ) -
Django: Update specific part of template by button click
I have a text field <input type="text" value="This is a test." name="mytextbox" size="10"/> and separated from that a button <button type = "button" class="btn btn-primary"> <font size="1">Run</font> </button> that should update a list and update the value of the text field itself. Sometimes forms are used in this context, but I would have to wrap the forms tag around the whole template when the input and button are separated on the screen. Since I am relatively new to Django, I would like to know the best strategy to solve the problem. a) Reload the complete page template with changed arguments/context b) Create a html template of the specific part that extends the main template and only try to render/update this one. c) Do something smarter. There are some answers in a (much older) post from 8 years ago but I am interested in the state-of-the-art solution. -
My login.view fails and say didnt return a http response object
I am having this trouble to make a login form for 2 different types of user. Since I implemented this code, my renderer is failing. def Login_View(request): context = {} user = request.user if request.method == 'POST': form = AuthencationForm(request.POST) if form.is_valid(): email = request.POST['email'] password = request.POST['password'] user = authenticate(request,email=email, password=password) if user is not None: if user.is_active: login(request, user) type_user = user.user_type if user.is_authenticated and type_user == "1": return redirect('requests' % request.user.FKLab_User.id) elif user.is_authenticated and type_user == "2": return redirect('distributor-view' % request.user.FKDistrib_User.id) return messages.info(request,"Your account is disabled.") return messages.info(request,"Username and password are incorrect.") else: form = AuthencationForm() return render(request, 'accounts/login.html', {'form': form}) This login view came from the user model, that is: class CustomUser(AbstractBaseUser, PermissionsMixin): USER_TYPE_CHOICES =( (1, 'LAB_USER'), (2, 'DISTRIB_USER') ) FKLab_User = models.ForeignKey('HospitalViewRoleForUsers', on_delete=models.PROTECT, null=True, blank= True) FKDistrib_User = models.ForeignKey('distrib_api.Distributor', on_delete=models.SET_NULL, null=True, blank= True) user_type = models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES, default=0, null=True, blank=True) email = models.EmailField(_('email address'), unique=True) name = models.CharField(max_length=255, blank=True, null=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) telephone = models.CharField(max_length=15, blank=True, null=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() class Meta: db_table = 'customuser' indexes = [ models.Index(fields=['name'], name='first_name_idx'), ] def __str__(self): return self.email I want to make a webapp where theres … -
Issue with djongo EmbeddedFields
I'm using Djongo with Django and MongoDB, however I am stuck at the following issue when trying to implement an embedded field ValueError: Value: [OrderedDict([('userID', 1), ('username', 'o'), ('admin', False)])] must be an instance of <class 'dict'> These are the models concerned: from djongo import models class groupMembership(models.Model): membershipID = models.ObjectIdField() userID = models.IntegerField() username = models.CharField(max_length=50) admin = models.BooleanField(default=False) class group(models.Model): groupID = models.ObjectIdField() title = models.CharField(max_length=100) createdDate = models.DateField() members = models.EmbeddedField(model_container = groupMembership, null = True) Here are the serializers I am using: class groupMembershipSerializer(serializers.ModelSerializer): class Meta: model=groupMembership fields=('membershipID', 'userID', 'username', 'admin') class groupSerializer(serializers.ModelSerializer): members = groupMembershipSerializer(many = True) class Meta: model=group fields=('groupID','title','createdDate','members') Error is thrown when I try to send in the following POST request: { "title" : "l", "createdDate" : "2021-07-07", "members" : [{ "userID" : "1", "username": "o", "admin" : "False" } ] } Any help is appreciated! -
Does this many-to-many relationship make sense?
I'm writing a django app and I have the following models below, however I am unsure about the relatinonships of order_id and product_id in DetailedOrder and customer_id in Demand model. In the DetailedOrder model, there can be multiple order_id (O0001) if the customer orders multiple product_id. Then the order_id can be used in the Order model to find who the customer was. Or should the product_id in the DetailedOrder be a many to many relationship because there can be multiple products for 1 order_id - i think this makes more sense. Also by this logic, does this mean customer_id in the Ordermodel should be a many-to-many relationship because there can be multiple customer_ids to multiple order_ids? Any advice is appreciated! class Customer(models.Model): customer_id = models.CharField(primary_key=True, max_length=150) customer_name = models.CharField(max_length=150, null=True) class Product(models.Model): product_id = models.CharField(primary_key=True, max_length=100) product_name = models.CharField(max_length=150) class Order(models.Model): order_id = models.CharField(primary_key=True, max_length=100) customer_id = models.ForeignKey(Customer, null=True, on_delete= models.SET_NULL) class DetailedOrder(models.Model): order_id = models.ForeignKey(Demand, null=True, on_delete= models.SET_NULL) product_id = models.ForeignKey(Product, null=True, on_delete= models.SET_NULL) quantity = models.IntegerField() -
Skip Django Rest Throttling Counter
How can I prevent Django rest throttling count the request when the user request is invalid or the server failed to complete the process? For example, I need params from the user, but when the user does not give the params, Django rest throttling still counts it. Is there any solution to skipping the throttling counter when the request is not successful? Example class OncePerHourAnonThrottle(AnonRateThrottle): rate = "1/hour" class Autoliker(APIView): throttle_classes = [OncePerHourAnonThrottle] def get(self, request): content = {"status": "get"} return Response(content) def post(self, request): post_url = request.POST.get("url", None) print(post_url) content = {"status": "post"} return Response(content) def throttled(self, request, wait): raise Throttled( detail={ "message": "request limit exceeded", "availableIn": f"{wait} seconds", "throttleType": "type", } ) -
Django Model for associating Favourites
Use case: Want to let an admin create favourite relationships between users. To do this, I am creating a model called Favourites. class Favourite(models.Model): user = models.ForeignKey(to=CustomUser, on_delete=models.CASCADE) otheruser = models.IntegerField() However, both user and otherusers are both objects in CustomUsers. In the admin console, when adding a favourite I get a list of users, but I do not get a list of other users obviously. What model field can I use so that when adding a favourite I get a list of users, and when choosing the otheruser that is also a list of users? -
I am taking Cs50 lecture3 Django in which there is a problem that not works the name variable we assigned to each path in urls.py, and create a link
this is my django+html code {% extends "tasks/layout.html" %} {% block body %} <h1>Tasks Lists</h1> <a href="[% url 'tasks:add' %]"> Add a task</a> {% endblock %} this is where i use varriable name add and link it to another page. Urls.py from django.urls import path from . import views app_name = "tasks" urlpatterns=[ path("",views.index,name="index"), path("add",views.add,name="add") ] this is where i use the varriable name "add". -
AttributeError: 'bool' object has no attribute 'rsplit' error on Django 2.x 3.x 4.x with postgres database
This error may point to a model but it is mainly an incompatibility with Postgres package. In a new postgres databases it may include following error when doing initial migration: "AssertionError: database connection isn't set to UTC" I got same error with Python 3.8 & 3.10 + Django 3 & 4. -
How do I construct a Complex Django Query where sometimes the conditions are ALL
Let's say I have three Choicefields and I know their values in my view. For example: fpriority = filtform["priority"].value() fstatus = filtform["status"].value() fassigned = filtform["assigned"].value() The values of each will be an integer (for example, 1-3) that relates to the appropriate column in the Table. So my first thoughts on Query is this: tasks = Task.objects.filter(Q(priority=fpriority) & Q( status=fstatus) & Q(assigned_to=fassigned)) The problem I have though, is that I also want a choice for all. So lets say I include zero (0) in each ChoiceField to signify ALL So now each of the above Q conditions must include the possibility that the variable is 0 and therefore means ALL for that part of the condition. Any thoughts on a clean way to do this?