Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django JWT Auth for custom model
I have a custom user model class User(models.Model): fields... It also has a email, password field among other detail fields. I want to use the simplejwt JWT authorization which takes email and password as input and generates JWT Tokens. Most tutorials include creating a superuser and passing username password of the superuser to get the token, But I want to do this for my custom user model. -
Best way to implement highly customized Django admin action
I'm trying to implement a custom Admin action that creates an OwnerInvoice object based on data from Receivable and Reservation objects. All Receivable and Reservation objects are related to only one Property object. Ideal workflow: Business admin selects property X to bill and shows a list of Reservation objects which are related to property X and haven't been billed yet. Admin can select which Reservation objects should be billed and a breakdown of the Reservation data selected is shown. On the same page, the admin should be able to choose from a list of Receivable objects (all related to property X and not yet billed). After selecting Receivables, a final page shows the breakdown of Reservation and Receivable objects and provides a total. By pressing save, an OwnerInvoice object is created and a PDF (OwnerInvoice method) is generated. The question: How would the StackOverflow community recommend I implement this kind of functionality into the Django admin? Possible ideas I've had but not sure if they would work with the above flow: Extend the OwnerInvoice's application app_index admin template to show a custom table containing Property object information. Use redirects for intermediate pages (using Reservation change_list and Receivable change_list). Extend the … -
Django Serializer saves the object twice
I have a database with songs. Every song has a mainartist and all other artists are listed in an M2M as artists. I'm consuming data the API like this: def populate_song(uuid): full_endpoint = settings.API_HOST + settings.GET_SONG_BY_ID + uuid headers = { 'x-app-id': APP_ID, 'x-api-key': API_KEY, } r = requests.get(full_endpoint, headers=headers) # Create Python object from JSON string. if 'object' in r.json(): try: song = r.json()['object'] song['duplicate'] = False existingsong = Song.objects.filter(uuid=song['uuid']).first() if existingsong: data = SongSerializer(existingsong, data=song) else: data = SongSerializer(data=song) data.is_valid(raise_exception=True) return data.save() except Exception as err: print('Error saving the song with ID:' + uuid) print(Exception, err) if 'errors' in r.json(): # if Song is not found or is giving an error, mark this in the DB as duplicate. Song.objects.filter(uuid=uuid).update(duplicate=True) return This is the serializer for the song: class SongSerializer(serializers.ModelSerializer): artists = ArtistSerializer(many=True, required=False) mainartist = ArtistSerializer(many=True, required=False) def create(self, validated_data): artists_data = validated_data.pop('artists', None) # AT THIS POINT THE ERROR BREAKS THE CODE song = Song.objects.create(**validated_data) for artist_data in artists_data: artist = Artist.objects.filter(uuid=artist_data.get('uuid')).first() if not artist: artist = Artist.objects.create(**artist_data) if not song.mainartist: song.mainartist = artist # populate mainartist with the first SC artist continue song.save() continue song.artists.add(artist) return song def update(self, instance, validated_data): artists_data = validated_data.pop('artists', None) instance.artists.clear() … -
can i launch a jango app from within pycharm without using terminal?
with other projects i've developed i have been able to hit 'run' to launch my application, and then shift+f10 from then on. it seems excessively cumbersome to have to launch the terminal and type python manage.py runserver every time i want to test something... is there a better way? can i write a python file like "run.py" with some script that will launch the app, or some other solution? i've searched for ages, and all i can find is a thousand tutorials telling me how to start a project, rather than how to launch it more easily. thanks -
Auto execute background tasks in django
I am trying to automatically run background tasks as soon as the server starts in django. Specifically, after the server boots and is running on localhost, I want it to run functions that fetch api data to fill my DB. What is the best way to do this? Is it celery? Django-background-tasks is outdated for the lastest version of Django. I am trying to mess around with redis/rq and rq works when attached to a view but I still dont know how to actually have django run anything upon server load. Any guidance would be appreciated. Thank you! -
Is using something like Celery the only way to make scheduled background tasks?
Is there any alternative to Celery and other outdated libs such as django background tasks to run tasks in x seconds interval? -
I want a certain python script to be run when a Django project starts. Where should it be placed?
Also where should things be configured so that this specific script runs first. -
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 …